package com.ruoyi.system.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.aliyun.oss.HttpMethod;
import com.aliyun.oss.OSS;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.doudian.open.api.order_addOrderRemark.OrderAddOrderRemarkRequest;
import com.doudian.open.api.order_addOrderRemark.OrderAddOrderRemarkResponse;
import com.doudian.open.api.order_addOrderRemark.param.OrderAddOrderRemarkParam;
import com.doudian.open.api.order_logisticsAdd.OrderLogisticsAddResponse;
import com.doudian.open.api.order_review.OrderReviewResponse;
import com.doudian.open.core.AccessToken;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.config.DouDianAPI;
import com.ruoyi.system.config.DouDianToken;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.vo.CommissionVo;
import com.ruoyi.system.domain.vo.OrderDetailVo;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.*;
import com.ruoyi.system.utils.*;
import com.ruoyi.system.utils.node.CommissionNote;
import com.ruoyi.system.utils.node.DoudianOrderSpec;
import com.ruoyi.system.utils.node.DoudianOrderUserTag;
import com.ruoyi.system.utils.node.LabelNote;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 订单Controller
 *
 * @author hjf
 * @date 2025-02-13
 */
@RestController
@RequestMapping("/hmk/order")
public class RxOrderController extends BaseController {
    @Autowired
    private OrderChannelMapper orderChannelMapper;
    @Autowired
    private IRxOrderService rxOrderService;

    @Autowired
    private RxOrderMapper rxOrderMapper;

    @Autowired
    private RxTelMapper rxTelMapper;

    @Autowired
    private RxOrderFollowMapper rxOrderFollowMapper;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private IRxSupplierService supplierService;

    @Autowired
    private IRxBusinessService businessService;

    @Autowired
    private IRxSupplierService rxSupplierService;

    @Autowired
    private OrderAuthenticationTimerMapper orderAuthenticationTimerMapper;

    @Autowired
    private SysReceiveOrderConfigMapper sysReceiveOrderConfigMapper;

    @Autowired
    private RxDoudianGoodsMapper rxDoudianGoodsMapper;

    @Autowired
    private IOrderChannelService orderChannelService;

    @Autowired
    private OSS ossClient;

    @Autowired
    private OrderAttachmentMapper oAM;

    @Autowired
    private KsOrderMapper kOM;

    @Autowired
    private KsReplyLogMapper kRLM;

    @Autowired
    private KsAttachmentMapper kAM;


    @Autowired
    private IKsReplyLogService ksReplyLogService;

    @Autowired
    private KsLetterMapper ksLetterMapper;

    @Autowired
    private OrderLetterMapper oLM;

    @PermitAll
    @GetMapping("/getReceiveOrderMainSwitchByUserId")
    public AjaxResult getReceiveOrderMainSwitchByUserId(SysReceiveOrderConfig sysReceiveOrderConfig) {
        List<SysReceiveOrderConfig> list = sysReceiveOrderConfigMapper.getReceiveOrderMainSwitchByUserId(sysReceiveOrderConfig);
        if (!CollectionUtils.isEmpty(list)) {
            return AjaxResult.success(list.get(0));
        }
        SysReceiveOrderConfig newSysReceiveOrderConfig = new SysReceiveOrderConfig();
        return AjaxResult.success(newSysReceiveOrderConfig);
    }

    /**
     * 查询订单列表
     */
    @PreAuthorize("@ss.hasPermi('hmk:order:list')")
    @GetMapping("/list")
    public TableDataInfo list(RxOrder rxOrder) {
        SysUser currentUser = SecurityUtils.getLoginUser().getUser();
        if (currentUser == null) {
            throw new ServiceException("用户未登录或会话已过期", 401);
        }


        List<SysRole> roles = currentUser.getRoles();
        boolean zhuBoQuery = roles.stream().anyMatch(role -> role.getRoleId() == 106L || role.getRoleId() == 111L);
        if (zhuBoQuery) {
            rxOrder.setDoudianOrderManageAuthorIds(Arrays.asList(currentUser.getUserId()));
        }

        boolean yunYingQuery = roles.stream().anyMatch(role -> role.getRoleId() == 105L);
        if (yunYingQuery) {
            rxOrder.setBusinessIds(Arrays.asList(165L));
        }


        boolean xieZhuanQuery = roles.stream().anyMatch(role -> role.getRoleId() == 107L);
        if (xieZhuanQuery) {
            rxOrder.setReceiveOrderUserId(String.valueOf(currentUser.getUserId()));
        }


        boolean keFuQuery = roles.stream().anyMatch(role -> role.getRoleId() == 109L);
        if (keFuQuery) {
            rxOrder.setReceiveOrderUserId(String.valueOf(currentUser.getUserId()));
        }

        boolean huiNao = roles.stream().anyMatch(role -> role.getRoleId() == 101L);
        if (huiNao) {
            rxOrder.setBusinessId(165L);
            List<Integer> states = new ArrayList<>();
            if (null == rxOrder.getStates()) {
                states.add(3);
                states.add(5);
                states.add(8);
                states.add(100);
            } else {
                if (rxOrder.getStates().contains(3)) {
                    states.add(3);
                }
                if (rxOrder.getStates().contains(5)) {
                    states.add(5);
                }
                if (rxOrder.getStates().contains(8)) {
                    states.add(8);
                }
                if (rxOrder.getStates().contains(100)) {
                    states.add(100);
                }
                List<Integer> targetStates = Arrays.asList(1, 2, 4, 6, 7, 9);
                if (rxOrder.getStates().stream().anyMatch(targetStates::contains)) {
                    states.add(888);
                }
            }
            rxOrder.setStates(states);
        }
        boolean qianXiLe = roles.stream().anyMatch(role -> role.getRoleId() == 110L);
        if (qianXiLe) {
            rxOrder.setDoudianOrderShopId("175974257");
        }
        if (StringUtils.isNotEmpty(rxOrder.getOrderFollowContent())) {
            List<Long> ids = rxOrderFollowMapper.selectIdsByLikeContent(rxOrder.getOrderFollowContent());
            rxOrder.setIds(ids);
            if (ids.size() == 0) {
                List<RxOrderVo> list = new ArrayList<>();
                return getDataTable(list);
            }
        }
        String telNumbers = rxOrder.getTelNumbers();
        if (StringUtils.isNotEmpty(telNumbers)) {
            String[] telNumberArray = telNumbers.split("\n");
            List<String> telNumberLists = Arrays.stream(telNumberArray).map(String::trim).distinct().collect(Collectors.toList());
            rxOrder.setTelNumberList(telNumberLists);
        }
        String serials = rxOrder.getSerials();
        if (StringUtils.isNotEmpty(serials)) {
            String[] serialArray = serials.split("\n");
            List<String> serialLists = Arrays.stream(serialArray).map(String::trim).distinct().collect(Collectors.toList());
            rxOrder.setSerialList(serialLists);
        }
        String douDianIds = rxOrder.getDouDianIds();
        if (StringUtils.isNotEmpty(douDianIds)) {
            String[] douDianIdArray = douDianIds.split("\n");
            List<String> douDianIdList = Arrays.stream(douDianIdArray).map(String::trim).distinct().collect(Collectors.toList());
            rxOrder.setDouDianIdsList(douDianIdList);
        }
        startPage();
        List<RxOrderVo> list = rxOrderService.selectRxOrderList(rxOrder);

        HashMap<String, Boolean> eMap = new HashMap();
        HashMap<String, RxOrderVo> map = new HashMap<>();
        if (null != list && list.size() > 0) {
            List<String> ids = list.stream().map(RxOrderVo::getId).collect(Collectors.toList());
            List<RxOrderVo> oFS = rxOrderMapper.selectOrderFollowByIds(ids);
            for (RxOrderVo orderFollow : oFS) {
                map.put(orderFollow.getOrderId(), orderFollow);
            }
            List<RxOrderFollow> orderFollowFails = rxOrderMapper.selectFailByOrderIds(ids);
            if (orderFollowFails.size() > 0) {
                Map<String, Long> oFGMap = orderFollowFails.stream().collect(Collectors.groupingBy(f -> String.valueOf(f.getOrderId()), Collectors.counting()));
                List<OrderAttachment> oAS = rxOrderMapper.selectByOrderIds(ids);
                Map<String, Long> oAMap = oAS.stream().collect(Collectors.groupingBy(f -> String.valueOf(f.getOrderId()), Collectors.counting()));
                for (String id : ids) {
                    Long fCount = oFGMap.get(id);
                    if (null != fCount) {
                        if (fCount > 0) {
                            Long aCount = oAMap.get(id);
                            if (null != aCount && fCount == aCount) {
                                eMap.put(id, true);
                            }
                        }
                    }
                }
            }
        }

        for (RxOrderVo rov : list) {
            Boolean eT = eMap.get(rov.getId());
            if (null != eT && eT) {
                rov.setEvidenceChainTag("1");
            } else {
                rov.setEvidenceChainTag("0");
            }
            if ("5".equals(rov.getState())) {
                if (2 == rov.getIsActivation() && null != rov.getActivationTime()) {
                    rov.setActivationTag("已激活" + DateUtils.timestampToStrMMDD(rov.getActivationTime()));
                    rov.getOtherTag().add(rov.getActivationTag());
                }

                if ("5".equals(rov.getState()) && 1 == rov.getIsActivation() && null != rov.getAuthTime() && null != rov.getManageId()) {
                    SysUser sysUser = sysUserService.selectUserById(rov.getManageId());
                    if (null != sysUser) {
                        rov.setAuthTag(sysUser.getNickName() + DateUtils.timestampToStrMMDD(rov.getAuthTime()));
                        rov.getOtherTag().add(rov.getAuthTag());
                    }
                }
            }
            if (2 == rov.getEmergentStatus()) {
                rov.getOtherTag().add("急");
            }
            if (null != rov) {
                RxOrderVo mapOrderVo = map.get(rov.getId());
                if (null != mapOrderVo) {
                    rov.setContent(mapOrderVo.getContent());
                    rov.setFollowTime(mapOrderVo.getFollowTime());
                }
            }
            List<LabelObj> labels = new ArrayList<>();
            labels = getLabelObjList2(rov);
            if (StringUtils.isNotEmpty(rov.getDefineLabel())) {
                LabelObj labelObj = new LabelObj();
                labelObj.setName(rov.getDefineLabel());
                labelObj.setNode(rov.getDefineLabelNotes());
                labels.add(labelObj);
            }
            rov.setLabelObjs(labels);
        }
        return getDataTable(list);
    }


    /**
     * 导出订单列表
     */
    @PreAuthorize("@ss.hasPermi('hmk:order:export')")
    @RepeatSubmit
    @PostMapping("/export")
    public void export(HttpServletResponse response, RxOrder rxOrder) {
        SysUser currentUser = SecurityUtils.getLoginUser().getUser();
        if (currentUser == null) {
            throw new ServiceException("用户未登录或会话已过期", 401);
        }

        List<SysRole> roles = currentUser.getRoles();
        boolean zhuBoQuery = roles.stream().anyMatch(role -> role.getRoleId() == 106L || role.getRoleId() == 111L);
        if (zhuBoQuery) {
            rxOrder.setDoudianOrderManageAuthorIds(Arrays.asList(currentUser.getUserId()));
        }

        boolean yunYingQuery = roles.stream().anyMatch(role -> role.getRoleId() == 105L);
        if (yunYingQuery) {
            rxOrder.setBusinessIds(Arrays.asList(165L));
        }


        boolean xieZhuanQuery = roles.stream().anyMatch(role -> role.getRoleId() == 107L);
        if (xieZhuanQuery) {
            rxOrder.setReceiveOrderUserId(String.valueOf(currentUser.getUserId()));
        }


        boolean keFuQuery = roles.stream().anyMatch(role -> role.getRoleId() == 109L);
        if (keFuQuery) {
            rxOrder.setReceiveOrderUserId(String.valueOf(currentUser.getUserId()));
        }
        boolean qianXiLe = roles.stream().anyMatch(role -> role.getRoleId() == 110L);
        if (qianXiLe) {
            rxOrder.setDoudianOrderShopId("175974257");
        }
        if (StringUtils.isNotEmpty(rxOrder.getOrderFollowContent())) {
            List<Long> ids = rxOrderFollowMapper.selectIdsByLikeContent(rxOrder.getOrderFollowContent());
            rxOrder.setIds(ids);
            if (ids.size() == 0) {
                List<RxOrderVo> list = new ArrayList<>();
                return;
            }
        }
        String telNumbers = rxOrder.getTelNumbers();
        if (StringUtils.isNotEmpty(telNumbers)) {
            String[] telNumberArray = telNumbers.split("\n");
            List<String> telNumberLists = Arrays.stream(telNumberArray).map(String::trim).distinct().collect(Collectors.toList());
            rxOrder.setTelNumberList(telNumberLists);
        }
        String serials = rxOrder.getSerials();
        if (StringUtils.isNotEmpty(serials)) {
            String[] serialArray = serials.split("\n");
            List<String> serialLists = Arrays.stream(serialArray).map(String::trim).distinct().collect(Collectors.toList());
            rxOrder.setSerialList(serialLists);
        }
        String douDianIds = rxOrder.getDouDianIds();
        if (StringUtils.isNotEmpty(douDianIds)) {
            String[] douDianIdArray = douDianIds.split("\n");
            List<String> douDianIdList = Arrays.stream(douDianIdArray).map(String::trim).distinct().collect(Collectors.toList());
            rxOrder.setDouDianIdsList(douDianIdList);
        }
        List<RxOrder> list = rxOrderMapper.selectRxOrderExportList(rxOrder);
        for (RxOrder ro : list) {
            if (null != ro.getTakeOrderTime() && null != ro.getReceiveOrderTime()) {
                ro.setTakeOrderTimeStr(WorkTimeCalculator.calculateWorkMinutesBetween(ro.getReceiveOrderTime(), ro.getTakeOrderTime()));
            }
            ro.setAddTime(com.ruoyi.system.utils.ExcelUtil.formatLongToDateTime(ro.getTime()));
            if (null != ro.getActivationTime()) {
                ro.setActivationTimeStr(com.ruoyi.system.utils.ExcelUtil.formatLongToDateTime(ro.getActivationTime()));
            }
            ro.setAuthtimeStr(com.ruoyi.system.utils.ExcelUtil.formatLongToDateTime(ro.getAuthtime()));
            ro.setSuccessfutimeStr(com.ruoyi.system.utils.ExcelUtil.formatLongToDateTime(ro.getSuccessfutime()));
            ro.setCustomAddressAllStr(ro.getCityId() + ro.getAreaId() + ro.getStreetId() + ro.getCustomAddress());
        }
        ExcelUtil<RxOrder> util = new ExcelUtil<RxOrder>(RxOrder.class);
        util.exportExcel(response, list, "订单数据");
    }


    @PreAuthorize("@ss.hasPermi('hmk:order:query')")
    @RepeatSubmit
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(rxOrderService.selectRxOrderById(id));
    }

    /**
     * 新增订单
     */
    @PreAuthorize("@ss.hasPermi('hmk:order:add')")
    @RepeatSubmit
    @PostMapping
    public AjaxResult add(@RequestBody RxOrder rxOrder) {
        return toAjax(rxOrderService.insertRxOrder(rxOrder));
    }

    /**
     * 修改订单
     */
    @PreAuthorize("@ss.hasPermi('hmk:order:edit')")
    @RepeatSubmit
    @PutMapping
    public AjaxResult edit(@RequestBody RxOrder rxOrder) {
        return toAjax(rxOrderService.updateRxOrder(rxOrder));
    }


    @PreAuthorize("@ss.hasPermi('hmk:order:editByIdAndCurrent')")
    @RepeatSubmit
    @PutMapping("/editByIdAndCurrent")
    public AjaxResult editByIdAndCurrent(@RequestBody RxOrder rxOrder) {
        if (StringUtils.isNotEmpty(rxOrder.getMaintainReason())) {
            RxOrder rxOrder1 = rxOrderService.selectRxOrderById(rxOrder.getId());
            if (null != rxOrder1.getMaintainManageId()) {
                throw new BaseException("维系人只能维系一次");
            }
            SysUser sysUser = SecurityUtils.getLoginUser().getUser();
            if (sysUser == null) {
                throw new ServiceException("用户未登录或会话已过期", 401);
            }
            if (StringUtils.isEmpty(sysUser.getNickName())) {
                sysUser = sysUserService.selectUserById(sysUser.getUserId());
            }
            rxOrder.setMaintainManageId(sysUser.getUserId());
            RxOrderFollow rxOrderFollow = new RxOrderFollow();
            rxOrderFollow.setFollowType("1");
            rxOrderFollow.setTitle("【认领维系】");
            rxOrderFollow.setOrderId(rxOrder.getId().intValue());
            rxOrderFollow.setManageId(sysUser.getUserId().intValue());
            rxOrderFollow.setContent(sysUser.getNickName() + "对该订单操作了认领维系," + rxOrder.getMaintainReason());
            rxOrderFollow.setTime(System.currentTimeMillis() / 1000);
            rxOrderFollowMapper.insertRxOrderFollow(rxOrderFollow);
            rxOrderService.updateRxOrder(rxOrder);
        }
        return AjaxResult.success();
    }

    @PreAuthorize("@ss.hasPermi('hmk:order:takeOrder')")
    @RepeatSubmit
    @PostMapping("/takeOrder")
    public AjaxResult takeOrder(@RequestBody RxOrder rxOrder) {
        RxOrder rxOrder1 = rxOrderService.selectRxOrderById(rxOrder.getId());
        if (rxOrder1 == null) {
            throw new ServiceException("没有查到该订单");
        }
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        if (sysUser == null) {
            throw new ServiceException("用户未登录或会话已过期", 401);
        }
        if (StringUtils.isEmpty(sysUser.getNickName())) {
            sysUser = sysUserService.selectUserById(sysUser.getUserId());
        }
        if (!String.valueOf(sysUser.getUserId()).equals(rxOrder1.getReceiveOrderUserId())) {
            throw new ServiceException("您无权揽收,仅能跟单人揽收!");
        }

        Date date = new Date();
        RxOrder uO = new RxOrder();
        uO.setId(rxOrder1.getId());
        uO.setState(3);
        uO.setTakeOrderTime(date);
        RxOrderFollow of = new RxOrderFollow();
        of.setTitle("【揽收订单】");
        of.setManageId(sysUser.getUserId().intValue());
        of.setContent(rxOrder.getContent());
        of.setOrderId(rxOrder.getId().intValue());
        if (null == rxOrder1.getReceiveOrderTime()) {
            rxOrder1.setReceiveOrderTime(date);
            uO.setReceiveOrderTime(date);
            of.setContent("跟单客服" + sysUser.getNickName() + "已揽收此单,分配时间:" + DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, rxOrder1.getReceiveOrderTime()) + ",揽收时间:" + DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, uO.getTakeOrderTime()) + ",揽单时长为:" + WorkTimeCalculator.calculateWorkMinutesBetween(rxOrder1.getReceiveOrderTime(), uO.getTakeOrderTime()) + "分钟." + rxOrder.getContent());
        } else {
            of.setContent("跟单客服" + sysUser.getNickName() + "已揽收此单,分配时间:" + DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, rxOrder1.getReceiveOrderTime()) + ",揽收时间:" + DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, uO.getTakeOrderTime()) + ",揽单时长为:" + WorkTimeCalculator.calculateWorkMinutesBetween(rxOrder1.getReceiveOrderTime(), uO.getTakeOrderTime()) + "分钟." + rxOrder.getContent());
        }
        of.setTime(System.currentTimeMillis() / 1000);
        rxOrderFollowMapper.insertRxOrderFollow(of);
        rxOrderService.updateRxOrder(uO);
        return AjaxResult.success();
    }


    @PreAuthorize("@ss.hasPermi('hmk:order:handDecrypt')")
    @RepeatSubmit
    @PostMapping("/handDecrypt")
    public AjaxResult handDecrypt(@RequestBody RxOrder rxOrder) throws IOException {
        RxOrderFollow rxOrderFollow = new RxOrderFollow();
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        if (sysUser == null) {
            throw new ServiceException("用户未登录或会话已过期", 401);
        }
        if (StringUtils.isEmpty(sysUser.getNickName())) {
            sysUser = sysUserService.selectUserById(sysUser.getUserId());
        }

        RxOrder oldRxOrder = rxOrderService.selectRxOrderById(rxOrder.getId());
        if (70L == oldRxOrder.getDoudianOrderStatus()) {
            throw new BaseException("该订单已退款不能再解密!");
        }
        OkHttpClient client = new OkHttpClient.Builder().build();
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        Map<String, String> map = new HashMap<>();
        map.put("douDianOrderId", oldRxOrder.getDoudianOrderId());
        map.put("shopId", oldRxOrder.getDoudianOrderShopId());
        okhttp3.RequestBody body = okhttp3.RequestBody.create(mediaType, JSON.toJSONString(map));
        Request request = new Request.Builder().url("http://101.126.139.13:8080/hmk/douDian/decryptByDouDianOrderId").post(body).addHeader("Content-Type", "application/json").build();
        Response response = client.newCall(request).execute();
        if (response.isSuccessful() && response.body() != null) {
            String json = response.body().string();
            AjaxResult decryptResult = JSON.parseObject(json, AjaxResult.class);
            if (null != decryptResult.get("data")) {
                RxOrder decryptRxOrder = JSON.parseObject(decryptResult.get("data").toString(), RxOrder.class);
                rxOrderFollow.setContent(sysUser.getNickName() + "对订单操作了重新解密,解密结果:[证件姓名:" + decryptRxOrder.getCustomName() + "][收件人电话:" + decryptRxOrder.getCustomTel() + "][详细地址:" + decryptRxOrder.getCustomAddress() + "][证件号:" + decryptRxOrder.getCustomNumber() + "]");
            } else {
                rxOrderFollow.setContent(sysUser.getNickName() + "对订单操作了重新解密,解密失败,请不要重复解密,复制抖店id并联系管理员!");
            }
        }
        rxOrder.setMaintainManageId(sysUser.getUserId());
        rxOrderFollow.setTitle("【重新解密】");
        rxOrderFollow.setOrderId(rxOrder.getId().intValue());
        rxOrderFollow.setManageId(sysUser.getUserId().intValue());
        rxOrderFollow.setTime(System.currentTimeMillis() / 1000);
        rxOrderFollowMapper.insertRxOrderFollow(rxOrderFollow);
        return AjaxResult.success();
    }


    @PreAuthorize("@ss.hasPermi('hmk:order:editOrderState5')")
    @RepeatSubmit
    @PutMapping("/editOrderState5")
    public AjaxResult editOrderState5(@RequestBody RxOrder rxOrder) {
        String content = rxOrder.getContent();
        if (StringUtils.isNotEmpty(content)) {
            SysUser sysUser = SecurityUtils.getLoginUser().getUser();
            if (sysUser == null) {
                throw new ServiceException("用户未登录或会话已过期", 401);
            }
            if (StringUtils.isEmpty(sysUser.getNickName())) {
                sysUser = sysUserService.selectUserById(sysUser.getUserId());
            }
            OrderChannel orderChannel = orderChannelMapper.selectOrderChannelById(Long.valueOf(rxOrder.getChannelId()));
            if (null == orderChannel) {
                throw new ServiceException("没有查到该渠道", 500);
            }
            Long time = System.currentTimeMillis() / 1000;
            RxOrder rxOrder1 = rxOrderService.selectRxOrderById(rxOrder.getId());
            rxOrder.setAuthtime(time);

            rxOrder.setContent(null);
            rxOrder.setState(5);
            rxOrder.setManageId(sysUser.getUserId());
            rxOrder.setEmergentStatus(1L);

            if (null != rxOrder1.getDefineLabelStatus() && 5L == rxOrder1.getDefineLabelStatus()) {
                rxOrder.setDefineLabelDelete(true);
            }
            RxOrderFollow rxOrderFollow = new RxOrderFollow();
            rxOrderFollow.setFollowType("2");
            rxOrderFollow.setTitle("【实名完成】");
            rxOrderFollow.setOrderId(rxOrder.getId().intValue());
            rxOrderFollow.setManageId(sysUser.getUserId().intValue());
            rxOrderFollow.setContent(sysUser.getNickName() + "将订单实名完成,下单渠道为" + orderChannel.getChannelName() + "/" + orderChannel.getChannelCode() + content);
            rxOrderFollow.setTime(time);
            if (null != rxOrder.getManageId()) {
                rxOrderFollow.setRemindManageId(rxOrder.getManageId().intValue());
            }

            if (null != rxOrder1.getDoudianOrderStatus() && 20L == rxOrder1.getDoudianOrderStatus()) {
                AccessToken token = DouDianToken.getToken(rxOrder1.getDoudianOrderShopId());
                DouDianAPI.logisticsAdd(rxOrder1.getDoudianOrderId(), token);
                rxOrderFollow.setTitle("【实名完成并发货】");
                rxOrderFollow.setContent(sysUser.getNickName() + "将订单实名完成,并将发货指令传给抖店." + content);
            }

            if (null != rxOrder1.getDoudianOrderStatus() && 10L == rxOrder1.getDoudianOrderStatus()) {

                OrderAuthenticationTimer oAT = new OrderAuthenticationTimer();
                oAT.setQuantity(0L);
                oAT.setCreateTime(new Date());
                oAT.setUpdateTime(oAT.getCreateTime());
                oAT.setOrderId(rxOrder1.getId());
                orderAuthenticationTimerMapper.insertOrderAuthenticationTimer(oAT);

            }
            rxOrderService.updateRxOrder(rxOrder);
            rxOrderFollowMapper.insertRxOrderFollow(rxOrderFollow);
        }
        return AjaxResult.success();
    }


    @PreAuthorize("@ss.hasPermi('hmk:order:editOrderBaoZhang')")
    @RepeatSubmit
    @PutMapping("/editOrderBaoZhang")
    public AjaxResult editOrderBaoZhang(@RequestBody RxOrder rxOrder) {
        String content = rxOrder.getContent();
        if (StringUtils.isNotEmpty(content)) {
            SysUser sysUser = SecurityUtils.getLoginUser().getUser();
            if (sysUser == null) {
                throw new ServiceException("用户未登录或会话已过期", 401);
            }
            if (StringUtils.isEmpty(sysUser.getNickName())) {
                sysUser = sysUserService.selectUserById(sysUser.getUserId());
            }
            RxOrder rxOrder1 = rxOrderService.selectRxOrderById(rxOrder.getId());
            Long oldBaoZhangUserId = rxOrder1.getBaozhangManageId();
            Long newBaoZhangUserId = sysUser.getUserId();
            if (null != oldBaoZhangUserId) {
                if (oldBaoZhangUserId != newBaoZhangUserId) {
                    throw new BaseException("该订单之前已有人报过账,两次报账人不一致!");
                }
            }
            Long time = System.currentTimeMillis() / 1000;

            RxOrderFollow rxOrderFollow = new RxOrderFollow();
            rxOrderFollow.setFollowType("3");
            rxOrderFollow.setTitle("【添加报账】");
            rxOrderFollow.setOrderId(rxOrder.getId().intValue());
            rxOrderFollow.setManageId(sysUser.getUserId().intValue());
            rxOrderFollow.setContent(sysUser.getNickName() + "将订单添加报账" + rxOrder.getBaozhangPrice() + "元," + content);
            rxOrderFollow.setTime(time);
            rxOrderFollow.setRemindManageId(rxOrder.getManageId().intValue());
            rxOrderFollowMapper.insertRxOrderFollow(rxOrderFollow);
            rxOrder.setBaozhangManageId(sysUser.getUserId());
            rxOrder.setContent(null);
            BigDecimal v = rxOrder1.getBaozhangPrice().add(rxOrder.getBaozhangPrice());
            rxOrder.setBaozhangPrice(v);
            rxOrderService.updateRxOrder(rxOrder);
        }
        return AjaxResult.success();
    }


    @PreAuthorize("@ss.hasPermi('hmk:order:editOrderLoser')")
    @RepeatSubmit
    @PutMapping("/editOrderLoser")
    public AjaxResult editOrderLoser(@RequestBody RxOrder rxOrder) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        if (sysUser == null) {
            throw new ServiceException("用户未登录或会话已过期", 401);
        }
        if (StringUtils.isEmpty(sysUser.getNickName())) {
            sysUser = sysUserService.selectUserById(sysUser.getUserId());
        }
        Long time = System.currentTimeMillis() / 1000;

        RxOrderFollow rxOrderFollow = new RxOrderFollow();
        rxOrderFollow.setFollowType("4");
        rxOrderFollow.setTitle("【交易失败】");
        rxOrderFollow.setOrderId(rxOrder.getId().intValue());
        rxOrderFollow.setManageId(sysUser.getUserId().intValue());
        rxOrderFollow.setContent(sysUser.getNickName() + "将订单交易失败," + rxOrder.getDefineLabel() + ":" + rxOrder.getDefineLabelNotes());
        rxOrderFollow.setTime(time);
        RxOrder oldOrder = rxOrderService.selectRxOrderById(rxOrder.getId());
        if (null != oldOrder.getDoudianOrderStatus() && oldOrder.getDoudianOrderStatus() == 10) {
            rxOrderFollow.setTitle("【交易失败+审核失败】");
            rxOrderFollow.setContent(sysUser.getNickName() + "将订单交易失败+审核失败." + rxOrder.getDefineLabel() + ":" + rxOrder.getDefineLabelNotes());
            AccessToken token = DouDianToken.getToken(oldOrder.getDoudianOrderShopId());
            DouDianAPI.review("400", oldOrder.getDoudianOrderId(), token);
        }
        rxOrderFollowMapper.insertRxOrderFollow(rxOrderFollow);
        RxOrder newRxOder = new RxOrder();
        newRxOder.setId(rxOrder.getId());
        newRxOder.setState(8);
        newRxOder.setFailureTime(System.currentTimeMillis() / 1000);
        newRxOder.setFailureReason(rxOrder.getDefineLabelNotes());
        newRxOder.setEmergentStatus(1L);
        rxOrderService.updateRxOrder(newRxOder);
        RxTel oldRxTel = rxTelMapper.selectRxTelByTel(oldOrder.getTelnumber());
        if (null != oldRxTel) {
            RxTel oldTelCopy = new RxTel();
            oldTelCopy.setId(oldRxTel.getId());
            oldTelCopy.setState(1);
            rxTelMapper.updateRxTel(oldTelCopy);
        }
        return AjaxResult.success();
    }


    @RepeatSubmit
    @Transactional
    @PreAuthorize("@ss.hasPermi('hmk:order:editOrderAddGenJin10')")
    @PutMapping("/editOrderAddGenJin10")
    public AjaxResult editOrderAddGenJin10(@RequestBody RxOrder queryOrder) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        if (sysUser == null) {
            throw new ServiceException("用户未登录或会话已过期", 401);
        }
        if (StringUtils.isEmpty(sysUser.getNickName())) {
            sysUser = sysUserService.selectUserById(sysUser.getUserId());
        }
        Long time = System.currentTimeMillis() / 1000;
        RxOrder oldOrder = rxOrderService.selectRxOrderById(queryOrder.getId());
        RxOrderFollow rxOrderFollow = new RxOrderFollow();
        rxOrderFollow.setTitle("【添加跟进】");
        rxOrderFollow.setOrderId(queryOrder.getId().intValue());
        rxOrderFollow.setManageId(sysUser.getUserId().intValue());
        rxOrderFollow.setTime(time);
        String displayStr = org.apache.commons.lang3.StringUtils.join(queryOrder.getDisplayObjects(), ",");
        rxOrderFollow.setDisplayobjects(displayStr);
        rxOrderFollow.setType(queryOrder.getType());
        if (null != queryOrder.getManageId()) {
            rxOrderFollow.setRemindManageId(queryOrder.getManageId().intValue());
        }
        RxOrder newRxOrder = new RxOrder();
        newRxOrder.setId(queryOrder.getId());
        newRxOrder.setEmergentStatus(queryOrder.getEmergentStatus());
        newRxOrder.setDefineLabelNotes(queryOrder.getDefineLabelNotes());
        newRxOrder.setDefineLabel(queryOrder.getDefineLabel());
        newRxOrder.setDefineLabelStatus(queryOrder.getDefineLabelStatus());
        String content = queryOrder.getDefineLabelNotes();
        if (StringUtils.isNotEmpty(queryOrder.getDefineLabel())) {
            content += "【" + queryOrder.getDefineLabel() + "】该标签在" + "";
        }
        if (null != queryOrder.getDefineLabelStatus()) {
            if (3L == queryOrder.getDefineLabelStatus()) {
                content += "处理中后自动失效";
            } else if (5L == queryOrder.getDefineLabelStatus()) {
                content += "已实名后自动失效";
            } else if (6L == queryOrder.getDefineLabelStatus()) {
                content += "已完成后自动失效";
            }
        }
        rxOrderFollow.setContent(content);
        rxOrderFollowMapper.insertRxOrderFollow(rxOrderFollow);
        rxOrderMapper.updateRxOrder(newRxOrder);
        if (null != queryOrder.getAuditUser()) {
            SysUser auditUser = sysUserService.selectUserById(queryOrder.getAuditUser());
            RxOrderFollow rxOrderFollow2 = new RxOrderFollow();
            rxOrderFollow2.setOrderId(queryOrder.getId().intValue());
            rxOrderFollow2.setManageId(sysUser.getUserId().intValue());
            rxOrderFollow2.setTime(time);
            rxOrderFollow2.setDisplayobjects(displayStr);
            rxOrderFollow2.setType(queryOrder.getType());
            rxOrderFollow2.setRemindManageId(Math.toIntExact(queryOrder.getAuditUser()));
            OrderLetter oL = new OrderLetter();
            oL.setOrderId(oldOrder.getSerial());
            oL.setIssuerUser(sysUser.getUserId());
            oL.setAuditUser(queryOrder.getAuditUser());
            oL.setIssuerContent(content);
            oL.setIssuerTime(new Date());
            oL.setIsAgree(0L);
            oL.setReplyStatus(0);
            if (queryOrder.getGoAudit()) {
                oL.setTitle(oldOrder.getCustomName() + oldOrder.getTelnumber() + "订单通知");
                rxOrderFollow2.setTitle("【发起弹窗通知】");
                rxOrderFollow2.setContent(sysUser.getNickName() + "向" + auditUser.getNickName() + "发起了弹窗通知,请" + auditUser.getNickName() + "尽快回复.通知内容:" + content);
                oL.setGoAudit(0L);
            } else {
                oL.setTitle(oldOrder.getCustomName() + oldOrder.getTelnumber() + "订单审批");
                rxOrderFollow2.setTitle("【发起弹窗审核】");
                rxOrderFollow2.setContent(sysUser.getNickName() + "向" + auditUser.getNickName() + "发起了弹窗审核,请" + auditUser.getNickName() + "尽快决策.审核内容:" + content);
                oL.setGoAudit(1L);
            }
            rxOrderFollowMapper.insertRxOrderFollow(rxOrderFollow2);
            oL.setOrderFollowId(rxOrderFollow2.getId());
            oLM.insertOrderLetter(oL);
        }
        return AjaxResult.success();
    }


    @RepeatSubmit
    @PreAuthorize("@ss.hasPermi('hmk:order:batchAddGenJin')")
    @PutMapping("/batchAddGenJin")
    public AjaxResult batchAddGenJin(@RequestBody RxOrder queryOrder) {
        if (CollectionUtils.isEmpty(queryOrder.getIds())) {
            throw new ServiceException("请先选择需要跟进的订单!");
        }
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        if (sysUser == null) {
            throw new ServiceException("用户未登录或会话已过期", 401);
        }
        if (StringUtils.isEmpty(sysUser.getNickName())) {
            sysUser = sysUserService.selectUserById(sysUser.getUserId());
        }
        Long time = System.currentTimeMillis() / 1000;

        List<RxOrderVo> oldOrders = rxOrderMapper.selectStateListByIds(queryOrder.getIds());
        List<RxOrder> newOrders = new ArrayList();
        List<RxOrderFollow> newOrderFollows = new ArrayList();
        for (RxOrderVo rv : oldOrders) {
            RxOrder newRxOrder = new RxOrder();
            newRxOrder.setId(Long.valueOf(rv.getId()));
            newRxOrder.setEmergentStatus(queryOrder.getEmergentStatus());
            newRxOrder.setDefineLabelNotes(queryOrder.getDefineLabelNotes());
            newRxOrder.setDefineLabel(queryOrder.getDefineLabel());
            newRxOrder.setDefineLabelStatus(queryOrder.getDefineLabelStatus());
            newOrders.add(newRxOrder);
            RxOrderFollow rxOrderFollow = new RxOrderFollow();
            rxOrderFollow.setTitle("【批量添加跟进】");
            rxOrderFollow.setOrderId(Integer.valueOf(rv.getId()));
            rxOrderFollow.setManageId(sysUser.getUserId().intValue());
            rxOrderFollow.setTime(time);
            String displayStr = org.apache.commons.lang3.StringUtils.join(queryOrder.getDisplayObjects(), ",");
            rxOrderFollow.setDisplayobjects(displayStr);
            rxOrderFollow.setType(queryOrder.getType());
            if (null != queryOrder.getManageId()) {
                rxOrderFollow.setRemindManageId(queryOrder.getManageId().intValue());
            }
            String content = queryOrder.getDefineLabelNotes();
            if (StringUtils.isNotEmpty(queryOrder.getDefineLabel())) {
                content += "【" + queryOrder.getDefineLabel() + "】该标签在" + "";
            }
            if (null != queryOrder.getDefineLabelStatus()) {
                if (3L == queryOrder.getDefineLabelStatus()) {
                    content += "处理中后自动失效";
                } else if (5L == queryOrder.getDefineLabelStatus()) {
                    content += "已实名后自动失效";
                } else if (6L == queryOrder.getDefineLabelStatus()) {
                    content += "已完成后自动失效";
                }
            }
            rxOrderFollow.setContent(content);
            newOrderFollows.add(rxOrderFollow);
        }
        rxOrderMapper.batchUpdateByGenJin10(newOrders);
        rxOrderFollowMapper.batchInsertRxOrderFollow(newOrderFollows);
        return AjaxResult.success();
    }


    /**
     * 修改客户信息
     *
     * @param queryOrder
     * @return
     */
    @RepeatSubmit
    @Transactional
    @PreAuthorize("@ss.hasPermi('hmk:order:editOrderAddGenJin20')")
    @PutMapping("/editOrderAddGenJin20")
    public AjaxResult editOrderAddGenJin20(@RequestBody RxOrder queryOrder) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        if (sysUser == null) {
            throw new ServiceException("用户未登录或会话已过期", 401);
        }
        if (StringUtils.isEmpty(sysUser.getNickName())) {
            sysUser = sysUserService.selectUserById(sysUser.getUserId());
        }
        Long time = System.currentTimeMillis() / 1000;
        RxOrder oldOrder = rxOrderService.selectRxOrderById(queryOrder.getId());
        RxOrderFollow rxOrderFollow = new RxOrderFollow();
        rxOrderFollow.setTitle("【修改客户信息】");
        rxOrderFollow.setOrderId(queryOrder.getId().intValue());
        rxOrderFollow.setManageId(sysUser.getUserId().intValue());
        rxOrderFollow.setTime(time);
        String displayStr = org.apache.commons.lang3.StringUtils.join(queryOrder.getDisplayObjects(), ",");
        rxOrderFollow.setDisplayobjects(displayStr);
        rxOrderFollow.setType(queryOrder.getType());
        if (null != queryOrder.getManageId()) {
            rxOrderFollow.setRemindManageId(queryOrder.getManageId().intValue());
        }
        RxOrder newRxOrder = new RxOrder();


        newRxOrder.setId(queryOrder.getId());
        newRxOrder.setEmergentStatus(queryOrder.getEmergentStatus());
        if (StringUtils.isNotEmpty(queryOrder.getCustomName())) {
            newRxOrder.setCustomName(queryOrder.getCustomName());
        }

        if (StringUtils.isNotEmpty(queryOrder.getCustomNumber()) && !queryOrder.getCustomNumber().contains("*")) {
            newRxOrder.setCustomNumber(queryOrder.getCustomNumber());
        }

        if (StringUtils.isNotEmpty(queryOrder.getCustomTel()) && !queryOrder.getCustomTel().contains("*")) {
            newRxOrder.setCustomTel(queryOrder.getCustomTel());
        }

        if (StringUtils.isNotEmpty(queryOrder.getCustomAddress())) {
            newRxOrder.setCustomAddress(queryOrder.getCustomAddress());
        }
        if (5L == oldOrder.getType() || 6L == oldOrder.getType()) {
            if (StringUtils.isNotEmpty(queryOrder.getShengId())) {
                newRxOrder.setShengId(queryOrder.getShengId());
            }

            if (StringUtils.isNotEmpty(queryOrder.getCityId())) {
                newRxOrder.setCityId(queryOrder.getCityId());
            }

            if (StringUtils.isNotEmpty(queryOrder.getAreaId())) {
                newRxOrder.setAreaId(queryOrder.getAreaId());
            }

            if (StringUtils.isNotEmpty(queryOrder.getStreetId())) {
                newRxOrder.setStreetId(queryOrder.getStreetId());
            }

            String content = type20AndDouDianContentStr(oldOrder, queryOrder, sysUser);
            rxOrderFollow.setContent(content);
        } else {
            if (StringUtils.isNotEmpty(queryOrder.getCustomPackage())) {
                newRxOrder.setCustomPackage(queryOrder.getCustomPackage());
            }

            if (null != queryOrder.getOrderprice() && BigDecimalUtils.isNotEmpty(queryOrder.getOrderprice())) {
                newRxOrder.setOrderprice(queryOrder.getOrderprice());
            }

            if (StringUtils.isNotEmpty(queryOrder.getCustomPackage())) {
                newRxOrder.setCustomPackage(queryOrder.getCustomPackage());
            }

            if (StringUtils.isNotEmpty(queryOrder.getOrderpriceNote())) {
                newRxOrder.setOrderpriceNote(queryOrder.getOrderpriceNote());
            }

            if (StringUtils.isNotEmpty(queryOrder.getLabelNotes())) {
                HashMap<String, String> map = new HashMap();
                if (StringUtils.isNotEmpty(queryOrder.getLabelNotes())) {
                    queryOrder.setLabelType("1");
                    map.put("type", "1");
                    map.put("notes", queryOrder.getLabelNotes());
                    String jsonStr = JSON.toJSONString(map);
                    String phpStr = JsonToPhp.jsonToPhp(jsonStr);
                    newRxOrder.setLabelType("1");
                    newRxOrder.setLabelNotes(phpStr);
                }
            }

            String content = type20ContentStr(oldOrder, queryOrder, sysUser);
            rxOrderFollow.setContent(content);
        }
        rxOrderFollowMapper.insertRxOrderFollow(rxOrderFollow);
        rxOrderMapper.updateRxOrder(newRxOrder);
        return AjaxResult.success();
    }


    @RepeatSubmit
    @Transactional
    @PreAuthorize("@ss.hasPermi('hmk:order:editOrderAddGenJin30')")
    @PutMapping("/editOrderAddGenJin30")
    public AjaxResult editOrderAddGenJin30(@RequestBody RxOrder queryOrder) throws InterruptedException {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        if (sysUser == null) {
            throw new ServiceException("用户未登录或会话已过期", 401);
        }
        if (StringUtils.isEmpty(sysUser.getNickName())) {
            sysUser = sysUserService.selectUserById(sysUser.getUserId());
        }
        Long time = System.currentTimeMillis() / 1000;
        RxOrderFollow rxOrderFollow = new RxOrderFollow();
        RxOrder oldOrder = rxOrderService.selectRxOrderById(queryOrder.getId());
        if (70L == oldOrder.getDoudianOrderStatus()) {
            throw new BaseException("当前抖店状态为已退款不能再次发货!");
        }
        AccessToken token = DouDianToken.getToken(oldOrder.getDoudianOrderShopId());
        boolean auditTag = false;
        if (oldOrder.getDoudianOrderStatus() == 10L && oldOrder.getDoudianOrderShopId().equals("104110047")) {
            DouDianAPI.review("200", oldOrder.getDoudianOrderId(), token);
            auditTag = true;
            Thread.sleep(2000L);
        } else if (oldOrder.getDoudianOrderShopId().equals("104110047")) {
            logger.info("当前是联通店铺-订单外部状态是:{}", oldOrder.getDoudianOrderStatus());
        }

        RxOrder newRxOrder = new RxOrder();


        newRxOrder.setId(queryOrder.getId());
        newRxOrder.setEmergentStatus(queryOrder.getEmergentStatus());
        newRxOrder.setKuaidiCode(queryOrder.getLogisticCompany());
        newRxOrder.setKuaidiMailno(queryOrder.getLogisticSerial());
        newRxOrder.setKuaidiPhone(queryOrder.getLogisticPhoneSuffix());
        rxOrderMapper.updateRxOrder(newRxOrder);
        OrderLogisticsAddResponse orderLogisticsAddResponse = DouDianAPI.logisticsAdd(oldOrder.getDoudianOrderId(), token);
        if ("10000".equals(orderLogisticsAddResponse.getCode()) && "QITA".equals(queryOrder.getLogisticCompany())) {
            rxOrderFollow.setTitle("【后台执行发货成功】");
            if (auditTag) {
                rxOrderFollow.setContent(sysUser.getNickName() + "将订单执行了审核通过并发货,物流公司:无需物流");
            } else {
                rxOrderFollow.setContent(sysUser.getNickName() + "将订单执行了发货,物流公司:无需物流");
            }
        } else if (!"10000".equals(orderLogisticsAddResponse.getCode())) {
            rxOrderFollow.setTitle("【后台执行发货失败】");
            rxOrderFollow.setContent(sysUser.getNickName() + "将订单执行了审核通过并发货,发货失败:" + orderLogisticsAddResponse.getSubMsg());
        }
        rxOrderFollow.setOrderId(queryOrder.getId().intValue());
        rxOrderFollow.setManageId(sysUser.getUserId().intValue());
        rxOrderFollow.setTime(time);
        rxOrderFollowMapper.insertRxOrderFollow(rxOrderFollow);
        return AjaxResult.success();
    }


    @RepeatSubmit
    @PreAuthorize("@ss.hasPermi('hmk:order:editOrderAddGenJin40')")
    @PutMapping("/editOrderAddGenJin40")
    public AjaxResult editOrderAddGenJin40(@RequestBody RxOrder queryOrder) throws InvocationTargetException, IllegalAccessException {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        if (sysUser == null) {
            throw new ServiceException("用户未登录或会话已过期", 401);
        }
        if (StringUtils.isEmpty(sysUser.getNickName())) {
            sysUser = sysUserService.selectUserById(sysUser.getUserId());
        }
        Long time = System.currentTimeMillis() / 1000;
        RxOrder oldOrder = rxOrderService.selectRxOrderById(queryOrder.getId());
        RxOrder newRxOrder = new RxOrder();


        newRxOrder.setId(queryOrder.getId());
        newRxOrder.setEmergentStatus(queryOrder.getEmergentStatus());
        RxOrderFollow rxOrderFollow = new RxOrderFollow();
        rxOrderFollow.setTitle("【添加标签】");
        rxOrderFollow.setOrderId(queryOrder.getId().intValue());
        rxOrderFollow.setManageId(sysUser.getUserId().intValue());
        rxOrderFollow.setTime(time);
        String displayStr = org.apache.commons.lang3.StringUtils.join(queryOrder.getDisplayObjects(), ",");
        rxOrderFollow.setDisplayobjects(displayStr);
        rxOrderFollow.setType(queryOrder.getType());
        if (null != queryOrder.getManageId()) {
            rxOrderFollow.setRemindManageId(queryOrder.getManageId().intValue());
        }
        String[] labelTypes = new String[0];
        if (null != oldOrder.getLabelType()) {
            labelTypes = oldOrder.getLabelType().split(",");
        }
        List<String> oldLabelTypes = Arrays.asList(labelTypes);
        List<String> newLabelTypes = new ArrayList<>();
        Set<String> labelTypeSet = new HashSet<>(Arrays.asList(labelTypes));
        if (StringUtils.isNotEmpty(queryOrder.getNote2Data())) {
            labelTypeSet.add("2");
            newLabelTypes.add("2");
        }
        if (StringUtils.isNotEmpty(queryOrder.getNote3Data())) {
            labelTypeSet.add("3");
            newLabelTypes.add("3");
        }
        if (StringUtils.isNotEmpty(queryOrder.getNote4Data())) {
            labelTypeSet.add("4");
            newLabelTypes.add("4");
        }
        if (StringUtils.isNotEmpty(queryOrder.getNote5Data())) {
            newLabelTypes.remove("3");
            labelTypeSet.remove("3");
        }
        List<String> added = newLabelTypes.stream().filter(item -> !oldLabelTypes.contains(item)).collect(Collectors.toList());
        List<String> removed = oldLabelTypes.stream().filter(item -> !newLabelTypes.contains(item)).collect(Collectors.toList());
        String labelStr = String.join(",", labelTypeSet);
        newRxOrder.setLabelType(labelStr);
        List<LabelNote> oldLabelNode = new ArrayList<>();
        if (StringUtils.isNotEmpty(oldOrder.getLabelNotes())) {
            String labelNodeStr = PhpToJson.phpToJson(oldOrder.getLabelNotes());
            oldLabelNode = JSON.parseArray(labelNodeStr, LabelNote.class);
        }
        List<LabelNote> newLabelNode = new ArrayList<>();
        String Content = sysUser.getNickName();
        rxOrderFollow.setContent(Content);
        if (StringUtils.isNotEmpty(queryOrder.getNote2Data())) {
            if (added.contains("2")) {
                LabelNote l = new LabelNote();
                l.setType("2");
                l.setNotes(queryOrder.getNote2Data());
                newLabelNode.add(l);
                rxOrderFollow.setContent(rxOrderFollow.getContent() + "添加了白名单标签,理由是:" + queryOrder.getNote2Data() + " ");
            }
        }
        if (StringUtils.isNotEmpty(queryOrder.getNote3Data())) {
            if (added.contains("3")) {
                LabelNote l = new LabelNote();
                l.setType("3");
                l.setNotes(queryOrder.getNote3Data());
                newLabelNode.add(l);
                rxOrderFollow.setContent(rxOrderFollow.getContent() + "添加了黑名单标签,理由是:" + queryOrder.getNote3Data() + " ");
            }
            if (removed.contains("3")) {
                LabelNote l = new LabelNote();
                l.setType("3");
                l.setNotes(queryOrder.getNote3Data());
                newLabelNode.add(l);
                rxOrderFollow.setContent(rxOrderFollow.getContent() + "取消了黑名单标签,理由是:" + queryOrder.getNote5Data() + " ");
            }
        }

        if (StringUtils.isNotEmpty(queryOrder.getNote4Data())) {
            if (added.contains("4")) {
                LabelNote l = new LabelNote();
                l.setType("4");
                l.setNotes(queryOrder.getNote4Data());
                newLabelNode.add(l);
                newRxOrder.setMaintainManageId(sysUser.getUserId());
                rxOrderFollow.setContent(rxOrderFollow.getContent() + "添加了维系单标签,理由是:" + queryOrder.getNote4Data() + " ");
            }
        }

        Map<String, LabelNote> labelNoteMap = new HashMap<>();
        for (LabelNote labelNote : oldLabelNode) {
            labelNoteMap.put(labelNote.getType(), labelNote);
        }
        for (LabelNote labelNote : newLabelNode) {
            labelNoteMap.put(labelNote.getType(), labelNote);
        }
        if (StringUtils.isNotEmpty(queryOrder.getNote5Data())) {
            labelNoteMap.remove("3");
        }
        List<LabelNote> mergedLabelNode = new ArrayList<>(labelNoteMap.values());
        String jsonStr = JSON.toJSONString(mergedLabelNode);
        String phpStr = JsonToPhp.jsonToPhp(jsonStr);
        newRxOrder.setLabelNotes(phpStr);
        rxOrderFollowMapper.insertRxOrderFollow(rxOrderFollow);
        rxOrderService.updateRxOrder(newRxOrder);
        return AjaxResult.success();
    }

    public String type20AndDouDianContentStr(RxOrder oldOrder, RxOrder newOrder, SysUser sysUser) {
        StringBuilder sb = new StringBuilder();
        sb.append(sysUser.getNickName()).append("将客户信息由【").append(oldOrder.getCustomName()).append(", ").append(oldOrder.getCustomNumber()).append(", ").append(oldOrder.getCustomTel()).append(", ").append(oldOrder.getShengId()).append(oldOrder.getCityId()).append(oldOrder.getAreaId()).append(oldOrder.getStreetId()).append(oldOrder.getCustomAddress()).append("】改为【").append(newOrder.getCustomName()).append(", ").append(newOrder.getCustomNumber()).append(", ").append(newOrder.getCustomTel()).append(", ").append(newOrder.getShengId()).append(newOrder.getCityId()).append(newOrder.getAreaId()).append(newOrder.getStreetId()).append(newOrder.getCustomAddress()).append("】");
        return sb.toString();
    }

    public String type20ContentStr(RxOrder oldOrder, RxOrder newOrder, SysUser sysUser) {
        StringBuilder sb = new StringBuilder();
        sb.append(sysUser.getNickName()).append("添加了客户信息: ").append(newOrder.getCustomName()).append(", ").append(newOrder.getCustomNumber()).append(", ").append(newOrder.getCustomTel()).append(", ").append(newOrder.getCustomAddress()).append(", ").append(newOrder.getCustomPackage()).append(", ").append("订单价格由").append(oldOrder.getOrderprice()).append("改为").append(newOrder.getOrderprice()).append("(").append(newOrder.getOrderpriceNote()).append(")");
        return sb.toString();
    }


    @PreAuthorize("@ss.hasPermi('hmk:order:editOrderActivation')")
    @PutMapping("/editOrderActivation")
    public AjaxResult editOrderActivation(@RequestBody RxOrder rxOrder) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        if (sysUser == null) {
            throw new ServiceException("用户未登录或会话已过期", 401);
        }
        if (StringUtils.isEmpty(sysUser.getNickName())) {
            sysUser = sysUserService.selectUserById(sysUser.getUserId());
        }

        List<RxOrder> queryLists = rxOrderMapper.selectRxOrderListByIdentificationNumber(rxOrder.getIdentificationNumber());
        if (!CollectionUtils.isEmpty(queryLists)) {
            throw new ServiceException("该用户标识号已经存在,被单号占用:" + queryLists.get(0).getSerial());
        }
        Long time = System.currentTimeMillis() / 1000;
        RxOrderFollow rxOrderFollow = new RxOrderFollow();
        rxOrderFollow.setFollowType("6");
        rxOrderFollow.setTitle("【打标激活】");
        rxOrderFollow.setOrderId(rxOrder.getId().intValue());
        rxOrderFollow.setManageId(sysUser.getUserId().intValue());
        rxOrderFollow.setContent(sysUser.getNickName() + "将订单打标已激活,请商户尽快申请完工.激活时间: " + rxOrder.getActivationTime() + "; 用户标识号:" + rxOrder.getIdentificationNumber() + "; 首充金额:" + rxOrder.getFirstChargePrice());
        rxOrderFollow.setTime(time);
        if (null != rxOrder.getManageId()) {
            rxOrderFollow.setRemindManageId(rxOrder.getManageId().intValue());
        }
        rxOrderFollowMapper.insertRxOrderFollow(rxOrderFollow);
        rxOrder.setActivationTime(DateUtils.dateToStringYYYYMMDD(rxOrder.getActivationTime()));
        rxOrder.setManageId(null);
        rxOrder.setType(null);
        rxOrder.setIsActivation(2L);
        rxOrderService.updateRxOrder(rxOrder);
        return AjaxResult.success();
    }


    @PreAuthorize("@ss.hasPermi('hmk:order:editOrderAuthBack')")
    @PutMapping("/editOrderAuthBack")
    public AjaxResult editOrderAuthBack(@RequestBody RxOrder rxOrder) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        if (sysUser == null) {
            throw new ServiceException("用户未登录或会话已过期", 401);
        }
        if (StringUtils.isEmpty(sysUser.getNickName())) {
            sysUser = sysUserService.selectUserById(sysUser.getUserId());
        }
        Long time = System.currentTimeMillis() / 1000;
        RxOrder rxOrder1 = rxOrderService.selectRxOrderById(rxOrder.getId());

        RxOrderFollow rxOrderFollow = new RxOrderFollow();
        rxOrderFollow.setFollowType("7");
        rxOrderFollow.setTitle("【回退实名】");
        rxOrderFollow.setOrderId(rxOrder.getId().intValue());
        rxOrderFollow.setManageId(sysUser.getUserId().intValue());
        rxOrderFollow.setContent(sysUser.getNickName() + "将已实名订单回退至处理中,请商户尽快跟进处理.原因: " + rxOrder.getContent());
        rxOrderFollow.setTime(time);
        if (null != rxOrder.getManageId()) {
            rxOrderFollow.setRemindManageId(rxOrder.getManageId().intValue());
        }
        rxOrderFollowMapper.insertRxOrderFollow(rxOrderFollow);
        if (null != rxOrder1.getDefineLabelStatus() && 3L == rxOrder1.getDefineLabelStatus()) {
            rxOrder.setDefineLabelDelete(true);
        }
        rxOrder.setEmergentStatus(2L);
        rxOrderMapper.updateRxOrderByAuthBack(rxOrder);
        return AjaxResult.success();
    }


    @PreAuthorize("@ss.hasPermi('hmk:order:editOrderByRecall')")
    @PutMapping("/editOrderByRecall")
    public AjaxResult editOrderByRecall(@RequestBody RxOrder rxOrder) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        if (sysUser == null) {
            throw new ServiceException("用户未登录或会话已过期", 401);
        }
        if (StringUtils.isEmpty(sysUser.getNickName())) {
            sysUser = sysUserService.selectUserById(sysUser.getUserId());
        }
        Long time = System.currentTimeMillis() / 1000;
        String state = " ";
        String oldUserName = " ";
        RxOrder rxOrder1 = rxOrderService.selectRxOrderById(rxOrder.getId());
        if (7 == rxOrder1.getState()) {
            state = "已弃单";
        } else if (8 == rxOrder1.getState()) {
            state = "已取消";
        } else if (3 == rxOrder1.getState()) {
            state = "处理中";
        }
        if (null != rxOrder1.getMaintainManageId()) {
            SysUser sysUser1 = sysUserService.selectUserById(rxOrder1.getMaintainManageId());
            oldUserName = sysUser1.getNickName();
        }
        RxOrderFollow rxOrderFollow = new RxOrderFollow();
        rxOrderFollow.setFollowType("8");
        rxOrderFollow.setTitle("【回调处理】");
        rxOrderFollow.setOrderId(rxOrder.getId().intValue());
        rxOrderFollow.setManageId(sysUser.getUserId().intValue());
        rxOrderFollow.setContent(sysUser.getNickName() + "将订单状态由" + state + "调回至处理中,并将维系人由" + oldUserName + "变更为" + sysUser.getNickName() + ".原因: " + rxOrder.getContent());
        rxOrderFollow.setTime(time);
        if (null != rxOrder.getManageId()) {
            rxOrderFollow.setRemindManageId(rxOrder.getManageId().intValue());
        }
        rxOrderFollowMapper.insertRxOrderFollow(rxOrderFollow);
        rxOrder.setState(3);
        rxOrder.setReceiveOrderUserId(sysUser.getUserId().toString());
        rxOrder.setMaintainManageId(sysUser.getUserId());
        LabelNote labelNote = new LabelNote();
        labelNote.setType("4");
        labelNote.setNotes(rxOrder.getContent());
        String jsonStr = JSON.toJSONString(labelNote);
        try {
            String phpStr = JsonToPhp.jsonToPhp(jsonStr);
            rxOrder.setLabelNotes(phpStr);
        } catch (Exception e) {
            logger.info("json:{}", jsonStr);
        }
        if (null != rxOrder1.getDefineLabelStatus() && 3L == rxOrder1.getDefineLabelStatus()) {
            rxOrder.setDefineLabelDelete(true);
        }
        rxOrderMapper.updateRxOrderByRecall(rxOrder);
        return AjaxResult.success();
    }


    @PreAuthorize("@ss.hasPermi('hmk:order:editOrderByCancellation')")
    @PutMapping("/editOrderByCancellation")
    public AjaxResult editOrderByCancellation(@RequestBody RxOrder rxOrder) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        if (sysUser == null) {
            throw new ServiceException("用户未登录或会话已过期", 401);
        }
        if (StringUtils.isEmpty(sysUser.getNickName())) {
            sysUser = sysUserService.selectUserById(sysUser.getUserId());
        }
        Long time = System.currentTimeMillis() / 1000;

        RxOrderFollow rxOrderFollow = new RxOrderFollow();
        rxOrderFollow.setFollowType("9");
        rxOrderFollow.setTitle("【订单废弃】");
        rxOrderFollow.setOrderId(rxOrder.getId().intValue());
        rxOrderFollow.setManageId(sysUser.getUserId().intValue());
        rxOrderFollow.setContent(sysUser.getNickName() + "将订单废弃," + rxOrder.getCause() + " : " + rxOrder.getContent());
        rxOrderFollow.setTime(time);
        rxOrderFollowMapper.insertRxOrderFollow(rxOrderFollow);
        rxOrder.setContent(null);
        rxOrder.setState(100);
        rxOrder.setDefineLabel(rxOrder.getCause());
        rxOrder.setDefineLabelNotes(rxOrder.getContent());
        rxOrderMapper.updateRxOrder(rxOrder);
        RxOrder oldOrder = rxOrderService.selectRxOrderById(rxOrder.getId());
        RxTel oldRxTel = rxTelMapper.selectRxTelByTel(oldOrder.getTelnumber());
        if (null != oldRxTel) {
            RxTel oldTelCopy = new RxTel();
            oldTelCopy.setId(oldRxTel.getId());
            oldTelCopy.setState(1);
            rxTelMapper.updateRxTel(oldTelCopy);
        }
        return AjaxResult.success();
    }


    @PreAuthorize("@ss.hasPermi('hmk:order:editOrderByDeal')")
    @PutMapping("/editOrderByDeal")
    public AjaxResult editOrderByDeal(@RequestBody RxOrder rxOrder) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        if (sysUser == null) {
            throw new ServiceException("用户未登录或会话已过期", 401);
        }
        if (StringUtils.isEmpty(sysUser.getNickName())) {
            sysUser = sysUserService.selectUserById(sysUser.getUserId());
        }
        Long time = System.currentTimeMillis() / 1000;
        RxOrder oldOrder = rxOrderService.selectRxOrderById(rxOrder.getId());
        if (1L == rxOrder.getCommissionpriceType()) {
            RxOrderFollow rxOrderFollow = new RxOrderFollow();
            rxOrderFollow.setFollowType("10");
            rxOrderFollow.setTitle("【交易成功】");
            rxOrderFollow.setOrderId(rxOrder.getId().intValue());
            rxOrderFollow.setManageId(sysUser.getUserId().intValue());
            if (StringUtils.isEmpty(rxOrder.getContent())) {
                rxOrderFollow.setContent(sysUser.getNickName() + "将订单交易成功,本订单即返给佣" + rxOrder.getCommissionprice() + "元.");
            } else {
                rxOrderFollow.setContent(sysUser.getNickName() + "将订单交易成功,本订单即返给佣" + rxOrder.getCommissionprice() + "元.备注: " + rxOrder.getContent());
            }
            rxOrderFollow.setTime(time);
            rxOrderFollowMapper.insertRxOrderFollow(rxOrderFollow);
            rxOrder.setContent(null);
            rxOrder.setState(6);
            rxOrder.setSuccessfutime(System.currentTimeMillis() / 1000);
            rxOrderMapper.updateRxOrder(rxOrder);
            RxTel oldRxTel = rxTelMapper.selectRxTelByTel(oldOrder.getTelnumber());
            if (null != oldRxTel) {
                rxTelMapper.deleteRxTelById(oldRxTel.getId());
            }
        } else if (2L == rxOrder.getCommissionpriceType()) {

            RxOrderFollow rxOrderFollow = new RxOrderFollow();
            rxOrderFollow.setFollowType("10");
            rxOrderFollow.setTitle("【交易成功】");
            rxOrderFollow.setOrderId(rxOrder.getId().intValue());
            rxOrderFollow.setManageId(sysUser.getUserId().intValue());
            List<CommissionNote> commissionNotes = new ArrayList<>();
            String content = "";
            if (rxOrder.getCommissionVos().size() > 0) {
                for (CommissionVo cv : rxOrder.getCommissionVos()) {
                    String idName = "【" + cv.getBusinessId() + "】" + cv.getUserName();
                    String oneStr = idName + cv.getRadio() + "%,";
                    content += oneStr;
                    CommissionNote commissionNote = new CommissionNote();
                    commissionNote.setId(cv.getBusinessId());
                    commissionNote.setName(idName);
                    commissionNote.setLv(cv.getRadio());
                    commissionNotes.add(commissionNote);
                }
                String jsonStr = JSONArray.toJSONString(commissionNotes);
                String phpStr = JsonToPhp.jsonToPhp(jsonStr);
                rxOrder.setCommissionpriceArr(phpStr);
            }
            String content2 = "";
            if (StringUtils.isNotEmpty(rxOrder.getContent())) {
                content2 = rxOrder.getContent();
            }
            rxOrderFollow.setContent(sysUser.getNickName() + "将订单交易成功,本订单后返佣金明细:" + content + " 备注: " + content2);
            rxOrderFollow.setTime(time);
            rxOrderFollowMapper.insertRxOrderFollow(rxOrderFollow);
            rxOrder.setContent(null);
            rxOrder.setState(6);
            rxOrder.setSuccessfutime(System.currentTimeMillis() / 1000);
            rxOrder.setCommissionpriceType(2L);
            if (null != oldOrder.getDefineLabelStatus() && 6L == oldOrder.getDefineLabelStatus()) {
                rxOrder.setDefineLabelDelete(true);
            }
            rxOrderMapper.updateRxOrder(rxOrder);
            RxTel oldRxTel = rxTelMapper.selectRxTelByTel(oldOrder.getTelnumber());
            if (null != oldRxTel) {
                rxTelMapper.deleteRxTelById(oldRxTel.getId());
            }
        }
        return AjaxResult.success();
    }


    @PreAuthorize("@ss.hasPermi('hmk:order:updateByTelNumber')")
    @PostMapping(value = "/updateByTelNumber")
    public AjaxResult updateByTelNumber(@RequestBody RxOrder newOrder) {
        Long time = System.currentTimeMillis() / 1000;
        RxTel newTel = rxTelMapper.selectRxTelByTel(newOrder.getTelnumber());
        if (null == newTel) {
            throw new BaseException("没有查到该号码");
        }
        if (1 != newTel.getState()) {
            throw new BaseException("该号码状态不为上架中,不能使用!");
        }
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        if (sysUser == null) {
            throw new ServiceException("用户未登录或会话已过期", 401);
        }
        if (StringUtils.isEmpty(sysUser.getNickName())) {
            sysUser = sysUserService.selectUserById(sysUser.getUserId());
        }
        RxOrder oldOrder = rxOrderService.selectRxOrderById(newOrder.getId());
        String oldTel = oldOrder.getTelnumber();
        int length = oldOrder.getSerial().length();
        String SerialPerStr = oldOrder.getSerial().substring(0, length - 11);
        String newSerial = SerialPerStr + newTel.getTel();
        oldOrder.setSerial(newSerial);
        oldOrder.setTelId(newTel.getId());
        oldOrder.setTelnumber(newTel.getTel());
        oldOrder.setPrice(BigDecimal.valueOf(newTel.getPrice()));
        oldOrder.setBill(BigDecimal.valueOf(newTel.getBill()));
        oldOrder.setUploadfloorprice(BigDecimal.valueOf(newTel.getUploadfloorprice()));
        RxBusiness business = businessService.selectRxBusinessById(165L);
        jieSuanJia(newTel, oldOrder, business);
        oldOrder.setClassname(String.valueOf(newTel.getClassId()));
        oldOrder.setAddteltime(time);
        oldOrder.setSegmentname(String.valueOf(newTel.getSegmentId()));
        oldOrder.setSuppliername(String.valueOf(newTel.getSupplierId()));
        oldOrder.setContent(newTel.getContent());
        rxOrderService.updateRxOrder(oldOrder);
        RxOrderFollow rxOrderFollow = new RxOrderFollow();
        String followStr = "";
        if (StringUtils.isEmpty(oldTel)) {
            followStr = sysUser.getNickName() + "将订单号码选择为【" + newOrder.getTelnumber() + "】";
            rxOrderFollow.setTitle("【选择号码】");
            rxOrderFollow.setFollowType("");
        } else {
            followStr = sysUser.getNickName() + "将订单号码由【" + oldTel + "】改为【" + newOrder.getTelnumber() + "】";
            rxOrderFollow.setTitle("【修改号码】");
        }
        rxOrderFollow.setOrderId(newOrder.getId().intValue());
        rxOrderFollow.setContent(followStr);
        rxOrderFollow.setTime(time);
        rxOrderFollowMapper.insertRxOrderFollow(rxOrderFollow);
        RxTel oldRxTel = rxTelMapper.selectRxTelByTel(oldTel);
        if (null != oldRxTel) {
            RxTel oldTelCopy = new RxTel();
            oldTelCopy.setId(oldRxTel.getId());
            oldTelCopy.setState(1);
            rxTelMapper.updateRxTel(oldTelCopy);
        }
        RxTel newTelCopy = new RxTel();
        newTelCopy.setId(newTel.getId());
        newTelCopy.setState(2);
        rxTelMapper.updateRxTel(newTelCopy);
        AccessToken token = DouDianToken.getToken(oldOrder.getDoudianOrderShopId());

        addOrderRemark(oldOrder.getDoudianOrderId(), newOrder.getTelnumber(), token);
        return AjaxResult.success();
    }


    @PreAuthorize("@ss.hasPermi('hmk:order:updateByTelNumber')")
    @PostMapping(value = "/updateOrderTelAndForce")
    public AjaxResult updateOrderTelAndForce(@RequestBody RxOrder queryOrder) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        RxOrder oldOrder = rxOrderMapper.selectRxOrderById(queryOrder.getId());
        if (null == oldOrder) {
            throw new BaseException("没有查到该订单");
        }

        RxTel oldRxTel = rxTelMapper.selectRxTelByTel(oldOrder.getTelnumber());
        if (null != oldRxTel) {
            RxTel oldTelCopy = new RxTel();
            oldTelCopy.setId(oldRxTel.getId());
            oldTelCopy.setState(1);
            rxTelMapper.updateRxTel(oldTelCopy);
        }
        RxOrder newOrder = new RxOrder();
        int len = oldOrder.getSerial().length();
        String serialStrPre = oldOrder.getSerial().substring(0, len - 11);
        String newSerial = serialStrPre + queryOrder.getTelnumber();
        newOrder.setSerial(newSerial);
        newOrder.setTelnumber(queryOrder.getTelnumber());
        newOrder.setId(queryOrder.getId());
        newOrder.setAddteltime(System.currentTimeMillis() / 1000);
        rxOrderMapper.updateOrderTelAndForce(newOrder);
        RxOrderFollow rxOrderFollow = new RxOrderFollow();
        rxOrderFollow.setTitle("【强行写入订单号码】");
        rxOrderFollow.setContent(sysUser.getNickName() + "将订单号码改为【" + queryOrder.getTelnumber() + "】上架号码中无此号,该订单号码被直接写入,订单编号已由" + oldOrder.getSerial() + "改为" + newSerial + ",请知悉.");
        rxOrderFollow.setOrderId(queryOrder.getId().intValue());
        rxOrderFollow.setManageId(sysUser.getUserId().intValue());
        rxOrderFollow.setTime(System.currentTimeMillis() / 1000);
        rxOrderFollowMapper.insertRxOrderFollow(rxOrderFollow);
        return AjaxResult.success();
    }


    @PreAuthorize("@ss.hasPermi('hmk:order:updateReceiveOrderUserId')")
    @PostMapping(value = "/updateReceiveOrderUserId")
    public AjaxResult updateReceiveOrderUserId(@RequestBody RxOrder rxOrder) {
        Long time = System.currentTimeMillis() / 1000;
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        if (sysUser == null) {
            throw new ServiceException("用户未登录或会话已过期", 401);
        }
        if (StringUtils.isEmpty(sysUser.getNickName())) {
            sysUser = sysUserService.selectUserById(sysUser.getUserId());
        }
        RxOrder rxOrder1 = rxOrderService.selectRxOrderById(rxOrder.getId());
        String followStr = "";
        RxOrderFollow rxOrderFollow = new RxOrderFollow();
        if (StringUtils.isEmpty(rxOrder1.getReceiveOrderUserId())) {
            SysUser newUser = sysUserService.selectUserById(Long.valueOf(rxOrder.getReceiveOrderUserId()));
            if (null != newUser) {
                followStr = sysUser.getNickName() + "将订单跟单人选择为【" + newUser.getNickName() + "】备注:" + rxOrder.getContent();
            }
            rxOrderFollow.setTitle("【选择跟单人】");
        } else {
            SysUser oldUser = sysUserService.selectUserById(Long.valueOf(rxOrder1.getReceiveOrderUserId()));
            SysUser newUser = sysUserService.selectUserById(Long.valueOf(rxOrder.getReceiveOrderUserId()));
            if (null != oldUser && null != newUser) {
                followStr = sysUser.getNickName() + "将订单跟单人由【" + oldUser.getNickName() + "】改为【" + newUser.getNickName() + "】备注:" + rxOrder.getContent();
            }
            rxOrderFollow.setTitle("【修改跟单人】");
        }
        rxOrderFollow.setOrderId(rxOrder.getId().intValue());
        rxOrderFollow.setContent(followStr);
        rxOrderFollow.setTime(time);
        rxOrderFollow.setManageId(Math.toIntExact(sysUser.getUserId()));
        rxOrderFollowMapper.insertRxOrderFollow(rxOrderFollow);
        RxOrder newRxOrder = new RxOrder();
        newRxOrder.setId(rxOrder.getId());
        newRxOrder.setReceiveOrderUserId(rxOrder.getReceiveOrderUserId());
        rxOrderService.updateRxOrder(newRxOrder);
        return AjaxResult.success();
    }


    @PreAuthorize("@ss.hasPermi('hmk:order:updateState6')")
    @PostMapping(value = "/updateState6")
    public AjaxResult updateState6(@RequestBody RxOrder rxOrder) throws IOException {
        Long time = System.currentTimeMillis() / 1000;
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        if (sysUser == null) {
            throw new ServiceException("用户未登录或会话已过期", 401);
        }
        if (StringUtils.isEmpty(sysUser.getNickName())) {
            sysUser = sysUserService.selectUserById(sysUser.getUserId());
        }
        RxOrderFollow rxOrderFollow = new RxOrderFollow();
        RxOrder newRxOder = new RxOrder();
        newRxOder.setId(rxOrder.getId());
        newRxOder.setState(6);
        newRxOder.setSuccessfutime(time);
        newRxOder.setCommissionpriceType(rxOrder.getCommissionpriceType());
        if (rxOrder.getCommissionpriceType() == 2 && null != rxOrder.getCommissionPriceArr() && rxOrder.getCommissionPriceArr().size() > 0) {
            String jsonString = JSONArray.toJSONString(rxOrder.getCommissionPriceArr());
            OkHttpClient client = new OkHttpClient().newBuilder().build();
            String encodedJson = URLEncoder.encode(jsonString, StandardCharsets.UTF_8.toString());
            Request request = new Request.Builder().url("http://www.haomaku.net/api/index/convertData?type=1&text=" + encodedJson).get().build();
            Response response = client.newCall(request).execute();
            String resPhpStr = response.body().string();
            newRxOder.setCommissionpriceArr(resPhpStr);
            String content = sysUser.getNickName() + "将订单竣工存档,本订单后返明细:";
            for (MyCommission m : rxOrder.getCommissionPriceArr()) {
                content += m.getName() + "返佣" + m.getLv() + "% ";
            }
            content += ".备注:" + rxOrder.getContent();
            rxOrderFollow.setContent(content);
        }

        if (rxOrder.getCommissionpriceType() == 1) {
            newRxOder.setCommissionprice(rxOrder.getCommissionprice());
            rxOrderFollow.setContent(sysUser.getNickName() + "订单竣工存档,本订单即返给佣" + rxOrder.getCommissionprice() + "元.备注:" + rxOrder.getContent());
        }
        rxOrderService.updateRxOrder(newRxOder);
        rxOrderFollow.setOrderId(rxOrder.getId().intValue());
        rxOrderFollow.setTitle("【竣工存档】");
        rxOrderFollow.setTime(time);
        rxOrderFollow.setManageId(Math.toIntExact(sysUser.getUserId()));
        rxOrderFollowMapper.insertRxOrderFollow(rxOrderFollow);
        RxOrder oldOrder = rxOrderService.selectRxOrderById(rxOrder.getId());
        RxTel oldRxTel = rxTelMapper.selectRxTelByTel(oldOrder.getTelnumber());
        if (null != oldRxTel) {
            rxTelMapper.deleteRxTelById(oldRxTel.getId());
        }
        return AjaxResult.success();
    }


    @PreAuthorize("@ss.hasPermi('hmk:order:batchUpdateState6')")
    @PostMapping(value = "/batchUpdateState6")
    public AjaxResult batchUpdateState6(@RequestBody RxOrder rxOrder) throws IOException {
        Long time = System.currentTimeMillis() / 1000;
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        if (sysUser == null) {
            throw new ServiceException("用户未登录或会话已过期", 401);
        }
        if (StringUtils.isEmpty(sysUser.getNickName())) {
            sysUser = sysUserService.selectUserById(sysUser.getUserId());
        }
        if (rxOrder.getIds().size() > 500) {
            throw new ServiceException("该操作需要调远端php接口,请选择低于500个订单");
        }
        List<RxOrderFollow> batchOF = new ArrayList<>();
        List<RxOrder> batchO = new ArrayList<>();
        List<RxOrderVo> rxOrderVos = rxOrderMapper.selectStateListByIds(rxOrder.getIds());
        OkHttpClient client = new OkHttpClient().newBuilder().build();
        int successCount = 0;
        int failCount = 0;
        for (RxOrderVo ov : rxOrderVos) {
            if (ov.getIsActivation() == 2 && !"6".equals(ov.getState())) {
                RxOrderFollow rxOrderFollow = new RxOrderFollow();
                RxOrder newRxOder = new RxOrder();
                newRxOder.setId(Long.valueOf(ov.getId()));
                newRxOder.setState(6);
                newRxOder.setSuccessfutime(time);
                newRxOder.setCommissionpriceType(rxOrder.getCommissionpriceType());
                if (rxOrder.getCommissionpriceType() == 2 && null != rxOrder.getCommissionPriceArr() && rxOrder.getCommissionPriceArr().size() > 0) {
                    String jsonString = JSONArray.toJSONString(rxOrder.getCommissionPriceArr());
                    String encodedJson = URLEncoder.encode(jsonString, StandardCharsets.UTF_8.toString());
                    Request request = new Request.Builder().url("http://www.haomaku.net/api/index/convertData?type=1&text=" + encodedJson).get().build();
                    Response response = client.newCall(request).execute();
                    String resPhpStr = response.body().string();
                    newRxOder.setCommissionpriceArr(resPhpStr);
                    String content = sysUser.getNickName() + "将订单竣工存档,本订单后返明细:";
                    for (MyCommission m : rxOrder.getCommissionPriceArr()) {
                        content += m.getName() + "返佣" + m.getLv() + "% ";
                    }
                    content += ".备注:" + rxOrder.getContent();
                    rxOrderFollow.setContent(content);
                }
                if (rxOrder.getCommissionpriceType() == 1) {
                    newRxOder.setCommissionprice(rxOrder.getCommissionprice());
                    rxOrderFollow.setContent(sysUser.getNickName() + "订单竣工存档,本订单即返给佣" + rxOrder.getCommissionprice() + "元.备注:" + rxOrder.getContent());
                }
                batchO.add(newRxOder);
                rxOrderFollow.setOrderId(Integer.valueOf(ov.getId()));
                rxOrderFollow.setTitle("【批量竣工】");
                rxOrderFollow.setTime(time);
                rxOrderFollow.setManageId(Math.toIntExact(sysUser.getUserId()));
                batchOF.add(rxOrderFollow);
                successCount += 1;
            } else {
                failCount += 1;
            }
        }
        if (batchO.size() > 0) {
            rxOrderMapper.batchUpdateState6(batchO);
        }
        if (batchOF.size() > 0) {
            rxOrderFollowMapper.batchInsertRxOrderFollow(batchOF);
        }
        for (RxOrderVo ov : rxOrderVos) {
            if (ov.getIsActivation() == 2 && !"6".equals(ov.getState())) {
                RxOrder oldOrder = rxOrderService.selectRxOrderById(Long.valueOf(ov.getId()));
                RxTel oldRxTel = rxTelMapper.selectRxTelByTel(oldOrder.getTelnumber());
                if (null != oldRxTel) {
                    rxTelMapper.deleteRxTelById(oldRxTel.getId());
                }
            }
        }
        String msg = "成功" + successCount + "条,失败(未激活或已完成):" + failCount + "条";
        return AjaxResult.success(msg);
    }


    /**
     * 订单详情页修改用户标识号
     *
     * @param rxOrder
     * @return
     */
    @PreAuthorize("@ss.hasPermi('hmk:order:updateIdentityNumber')")
    @PostMapping(value = "/updateIdentityNumber")
    public AjaxResult updateIdentityNumber(@RequestBody RxOrder rxOrder) {
        Long time = System.currentTimeMillis() / 1000;
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        if (sysUser == null) {
            throw new ServiceException("用户未登录或会话已过期", 401);
        }
        if (StringUtils.isEmpty(sysUser.getNickName())) {
            sysUser = sysUserService.selectUserById(sysUser.getUserId());
        }
        RxOrder rxOrder1 = rxOrderService.selectRxOrderById(rxOrder.getId());
        String followStr = "";
        if (StringUtils.isEmpty(rxOrder1.getIdentificationNumber())) {
            followStr = sysUser.getNickName() + "将用户标识号设置为了【" + rxOrder.getIdentificationNumber() + "】";
        } else {
            followStr = sysUser.getNickName() + "将用户标识号由【" + rxOrder1.getIdentificationNumber() + "】改为【" + rxOrder.getIdentificationNumber() + "】";

        }
        RxOrderFollow rxOrderFollow = new RxOrderFollow();
        rxOrderFollow.setTitle("【修改用户标识号】");
        rxOrderFollow.setOrderId(rxOrder.getId().intValue());
        rxOrderFollow.setContent(followStr);
        rxOrderFollow.setTime(time);
        rxOrderFollowMapper.insertRxOrderFollow(rxOrderFollow);
        rxOrderService.updateRxOrder(rxOrder);
        return AjaxResult.success();
    }


    @PreAuthorize("@ss.hasPermi('hmk:order:updateFirstChargePrice')")
    @PostMapping(value = "/updateFirstChargePrice")
    public AjaxResult updateFirstChargePrice(@RequestBody RxOrder rxOrder) {
        Long time = System.currentTimeMillis() / 1000;
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        if (sysUser == null) {
            throw new ServiceException("用户未登录或会话已过期", 401);
        }
        if (StringUtils.isEmpty(sysUser.getNickName())) {
            sysUser = sysUserService.selectUserById(sysUser.getUserId());
        }
        RxOrder rxOrder1 = rxOrderService.selectRxOrderById(rxOrder.getId());
        String followStr = "";
        if (null == rxOrder1.getFirstChargePrice()) {
            followStr = sysUser.getNickName() + "将首充金额设置为了【" + rxOrder.getFirstChargePrice() + "】";
        } else {
            followStr = sysUser.getNickName() + "将首充金额由【" + rxOrder1.getFirstChargePrice() + "】改为【" + rxOrder.getFirstChargePrice() + "】";

        }
        RxOrderFollow rxOrderFollow = new RxOrderFollow();
        rxOrderFollow.setTitle("【修改首充金额】");
        rxOrderFollow.setOrderId(rxOrder.getId().intValue());
        rxOrderFollow.setContent(followStr);
        rxOrderFollow.setTime(time);
        rxOrderFollowMapper.insertRxOrderFollow(rxOrderFollow);
        rxOrderService.updateRxOrder(rxOrder);
        return AjaxResult.success();
    }


    @PreAuthorize("@ss.hasPermi('hmk:order:updateGaiJia')")
    @PostMapping(value = "/updateGaiJia")
    public AjaxResult updateGaiJia(@RequestBody RxOrder rxOrder) {
        Long time = System.currentTimeMillis() / 1000;
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        if (sysUser == null) {
            throw new ServiceException("用户未登录或会话已过期", 401);
        }
        if (StringUtils.isEmpty(sysUser.getNickName())) {
            sysUser = sysUserService.selectUserById(sysUser.getUserId());
        }
        RxOrder rxOrder1 = rxOrderService.selectRxOrderById(rxOrder.getId());
        String followStr = sysUser.getNickName() + "将";
        if (null != rxOrder1.getOrderprice() && null != rxOrder.getOrderprice()) {
            followStr += "订单价格由" + rxOrder1.getOrderprice() + "元改为" + rxOrder.getOrderprice() + "元;";
        }

        if (null != rxOrder1.getSettlementprice() && null != rxOrder.getSettlementprice()) {
            followStr += "结算价由" + rxOrder1.getSettlementprice() + "元改为" + rxOrder.getSettlementprice() + "元;";
        }

        if (null != rxOrder1.getUploadfloorprice() && null != rxOrder.getUploadfloorprice()) {
            followStr += "上传底价由" + rxOrder1.getUploadfloorprice() + "元改为" + rxOrder.getUploadfloorprice() + "元";
        }
        RxOrderFollow rxOrderFollow = new RxOrderFollow();
        rxOrderFollow.setTitle("【改价】");
        rxOrderFollow.setOrderId(rxOrder.getId().intValue());
        rxOrderFollow.setContent(followStr);
        rxOrderFollow.setTime(time);
        rxOrderFollowMapper.insertRxOrderFollow(rxOrderFollow);
        rxOrderService.updateRxOrder(rxOrder);
        return AjaxResult.success();
    }


    @PreAuthorize("@ss.hasPermi('hmk:order:batchUpdatePrice')")
    @PostMapping(value = "/batchUpdatePrice")
    public AjaxResult batchUpdatePrice(@RequestBody RxOrder rxOrder) {
        Long time = System.currentTimeMillis() / 1000;
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        if (sysUser == null) {
            throw new ServiceException("用户未登录或会话已过期", 401);
        }
        if (StringUtils.isEmpty(sysUser.getNickName())) {
            sysUser = sysUserService.selectUserById(sysUser.getUserId());
        }
        int orderPrice = 0;
        int settlementPrice = 0;
        int uploadfloorPrice = 0;
        List<RxOrderFollow> batchOrderFollow = new ArrayList<>();
        List<RxOrder> batchOrder = new ArrayList<>();
        for (Long id : rxOrder.getIds()) {
            RxOrder rxOrder1 = rxOrderService.selectRxOrderById(id);
            if (null == rxOrder1) {
                continue;
            }
            String followStr = sysUser.getNickName() + "将";
            RxOrderFollow rxOrderFollow = new RxOrderFollow();
            rxOrderFollow.setTitle("【批量改价】");
            rxOrderFollow.setOrderId(id.intValue());

            rxOrderFollow.setManageId(sysUser.getUserId().intValue());
            rxOrderFollow.setTime(time);
            RxOrder rxOrder2 = new RxOrder();
            rxOrder2.setId(id);
            rxOrder2.setIsStoremsg(rxOrder1.getIsStoremsg());
            if (null != rxOrder.getOrderprice() && 2 == rxOrder1.getType()) {
                if (null != rxOrder1.getOrderprice()) {
                    if (0 != rxOrder.getOrderprice().compareTo(rxOrder1.getOrderprice())) {
                        rxOrder2.setOrderprice(rxOrder.getOrderprice());
                        orderPrice += 1;
                        if (null != rxOrder1.getOrderprice() && null != rxOrder.getOrderprice()) {
                            followStr += "订单价格由" + rxOrder1.getOrderprice() + "元改为" + rxOrder.getOrderprice() + "元;";
                        }
                    }
                } else {
                    rxOrder2.setOrderprice(rxOrder.getOrderprice());
                    orderPrice += 1;
                    if (null != rxOrder1.getOrderprice() && null != rxOrder.getOrderprice()) {
                        followStr += "订单价格由" + rxOrder1.getOrderprice() + "元改为" + rxOrder.getOrderprice() + "元;";
                    }
                }
            }
            if (null != rxOrder.getSettlementprice()) {
                if (null != rxOrder1.getSettlementprice()) {
                    if (0 != rxOrder.getSettlementprice().compareTo(rxOrder1.getSettlementprice())) {
                        rxOrder2.setSettlementprice(rxOrder.getSettlementprice());
                        settlementPrice += 1;
                        if (null != rxOrder1.getSettlementprice() && null != rxOrder.getSettlementprice()) {
                            followStr += "结算价由" + rxOrder1.getSettlementprice() + "元改为" + rxOrder.getSettlementprice() + "元;";
                        }
                    }
                } else {
                    rxOrder2.setSettlementprice(rxOrder.getSettlementprice());
                    settlementPrice += 1;
                    if (null != rxOrder1.getSettlementprice() && null != rxOrder.getSettlementprice()) {
                        followStr += "结算价由" + rxOrder1.getSettlementprice() + "元改为" + rxOrder.getSettlementprice() + "元;";
                    }
                }
            }
            if (null != rxOrder.getUploadfloorprice()) {
                if (null != rxOrder1.getUploadfloorprice()) {
                    if (0 != rxOrder.getUploadfloorprice().compareTo(rxOrder1.getUploadfloorprice())) {
                        rxOrder2.setUploadfloorprice(rxOrder.getUploadfloorprice());
                        uploadfloorPrice += 1;
                        if (null != rxOrder1.getUploadfloorprice() && null != rxOrder.getUploadfloorprice()) {
                            followStr += "上传底价由" + rxOrder1.getUploadfloorprice() + "元改为" + rxOrder.getUploadfloorprice() + "元";
                        }
                    }
                } else {
                    rxOrder2.setUploadfloorprice(rxOrder.getUploadfloorprice());
                    uploadfloorPrice += 1;
                    if (null != rxOrder1.getUploadfloorprice() && null != rxOrder.getUploadfloorprice()) {
                        followStr += "上传底价由" + rxOrder1.getUploadfloorprice() + "元改为" + rxOrder.getUploadfloorprice() + "元";
                    }
                }
            }
            rxOrderFollow.setContent(followStr);
            batchOrderFollow.add(rxOrderFollow);
            batchOrder.add(rxOrder2);
        }
        if (batchOrderFollow.size() > 0) {
            rxOrderFollowMapper.batchInsertRxOrderFollow(batchOrderFollow);
        }
        if (batchOrder.size() > 0) {
            rxOrderMapper.batchUpdateRxOrder(batchOrder);
        }
        String resStr = "";
        if (orderPrice > 0) {
            resStr += "订单价修改成功" + orderPrice + "; ";
        }
        if (settlementPrice > 0) {
            resStr += "结算价修改成功" + settlementPrice + "; ";
        }
        if (uploadfloorPrice > 0) {
            resStr += "上传底价修改成功" + uploadfloorPrice + "; ";
        }
        if (StringUtils.isEmpty(resStr)) {
            resStr = "没有值被修改!";
        }
        return AjaxResult.success(resStr);
    }


    @PreAuthorize("@ss.hasPermi('hmk:order:updateSupplier')")
    @PostMapping(value = "/updateSupplier")
    public AjaxResult updateSupplier(@RequestBody RxOrder rxOrder) {
        Long time = System.currentTimeMillis() / 1000;
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        if (sysUser == null) {
            throw new ServiceException("用户未登录或会话已过期", 401);
        }
        if (StringUtils.isEmpty(sysUser.getNickName())) {
            sysUser = sysUserService.selectUserById(sysUser.getUserId());
        }
        RxOrder rxOrder1 = rxOrderService.selectRxOrderById(rxOrder.getId());
        String followStr = "";
        if (StringUtils.isEmpty(rxOrder1.getSuppliername())) {
            RxSupplier newSupplier = supplierService.selectRxSupplierById(Long.valueOf(rxOrder.getSuppliername()));
            if (null != newSupplier) {
                followStr = sysUser.getNickName() + "将订单号码仓选择为【" + rxOrder.getSuppliername() + "】";
            }
        } else {
            RxSupplier newSupplier = supplierService.selectRxSupplierById(Long.valueOf(rxOrder.getSuppliername()));
            if (null != newSupplier) {
                followStr = sysUser.getNickName() + "将订单号码仓由【" + rxOrder1.getSuppliername() + "】改为【" + newSupplier.getTitle() + "】";
            }
        }
        RxOrderFollow rxOrderFollow = new RxOrderFollow();
        rxOrderFollow.setTitle("【修改号码仓】");
        rxOrderFollow.setOrderId(rxOrder.getId().intValue());
        rxOrderFollow.setManageId(sysUser.getUserId().intValue());
        rxOrderFollow.setContent(followStr);
        rxOrderFollow.setTime(time);
        rxOrderFollowMapper.insertRxOrderFollow(rxOrderFollow);
        rxOrderService.updateRxOrder(rxOrder);
        return AjaxResult.success();
    }


    @PreAuthorize("@ss.hasPermi('hmk:order:auditSuccess')")
    @Transactional
    @RepeatSubmit
    @PostMapping(value = "/auditSuccess")
    public AjaxResult auditSuccess(@RequestBody RxOrder rxOrder) {
        Long time = System.currentTimeMillis() / 1000;
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        if (sysUser == null) {
            throw new ServiceException("用户未登录或会话已过期", 401);
        }
        if (StringUtils.isEmpty(sysUser.getNickName())) {
            sysUser = sysUserService.selectUserById(sysUser.getUserId());
        }
        RxOrder rxOrder1 = rxOrderService.selectRxOrderById(rxOrder.getId());
        if (null == rxOrder1) {
            throw new BaseException("未查到该订单");
        }
        AccessToken token = DouDianToken.getToken(rxOrder1.getDoudianOrderShopId());
        OrderReviewResponse reviewResponse = DouDianAPI.review("200", rxOrder1.getDoudianOrderId(), token);
        RxOrderFollow rxOrderFollow = new RxOrderFollow();
        if ("10000".equals(reviewResponse.getCode())) {
            rxOrderFollow.setTitle("【审核成功】");
            rxOrderFollow.setContent(sysUser.getNickName() + "对订单操作了审核成功,抖店已同步!" + rxOrder.getContent());
        } else {
            rxOrderFollow.setTitle("【审核成功(业务处理失败)】");
            rxOrderFollow.setContent(sysUser.getNickName() + "对订单操作了审核成功,抖店业务处理失败!" + reviewResponse.getSubMsg());
        }
        rxOrderFollow.setOrderId(rxOrder.getId().intValue());
        rxOrderFollow.setManageId(sysUser.getUserId().intValue());
        rxOrderFollow.setTime(time);
        rxOrderFollowMapper.insertRxOrderFollow(rxOrderFollow);
        return AjaxResult.success();
    }


    @Transactional
    @RepeatSubmit
    @PreAuthorize("@ss.hasPermi('hmk:order:auditFail')")
    @PostMapping(value = "/auditFail")
    public AjaxResult auditFail(@RequestBody RxOrder rxOrder) throws InterruptedException {
        Long time = System.currentTimeMillis() / 1000;
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        if (sysUser == null) {
            throw new ServiceException("用户未登录或会话已过期", 401);
        }
        if (StringUtils.isEmpty(sysUser.getNickName())) {
            sysUser = sysUserService.selectUserById(sysUser.getUserId());
        }
        RxOrder oldOrder = rxOrderService.selectRxOrderById(rxOrder.getId());
        if (null == oldOrder) {
            throw new BaseException("未查到该订单");
        }
        RxOrderFollow rxOrderFollow = new RxOrderFollow();
        RxOrderFollow rxOrderFollow2 = new RxOrderFollow();
        AccessToken token = DouDianToken.getToken(oldOrder.getDoudianOrderShopId());
        OrderReviewResponse reviewResponse = DouDianAPI.review("400", oldOrder.getDoudianOrderId(), token);
        if ("10000".equals(reviewResponse.getCode())) {
            rxOrderFollow.setTitle("【审核失败】");
            rxOrderFollow.setContent(sysUser.getNickName() + "对订单操作了审核失败,已发送指令给抖店！" + rxOrder.getContent());
            if (oldOrder.getState() == 5 || BigDecimal.ZERO.compareTo(oldOrder.getBaozhangPrice()) != 0) {
            } else {
                RxOrder newRxOrder = new RxOrder();
                newRxOrder.setId(rxOrder.getId());
                newRxOrder.setState(8);
                rxOrderService.updateRxOrder(newRxOrder);
                rxOrderFollow.setContent(sysUser.getNickName() + "对订单操作了审核失败,已发送指令给抖店！" + rxOrder.getContent());
                rxOrderFollow2.setTitle("【交易失败(自动)】");
                rxOrderFollow2.setContent("订单操作了审核失败,系统自动将订单交易失败");
                rxOrderFollow2.setOrderId(rxOrder.getId().intValue());
                rxOrderFollow2.setManageId(sysUser.getUserId().intValue());
                rxOrderFollow2.setTime(time);
            }
            RxTel oldRxTel = rxTelMapper.selectRxTelByTel(oldOrder.getTelnumber());
            if (null != oldRxTel) {
                RxTel oldTelCopy = new RxTel();
                oldTelCopy.setId(oldRxTel.getId());
                oldTelCopy.setState(1);
                rxTelMapper.updateRxTel(oldTelCopy);
            }
        } else {
            rxOrderFollow.setTitle("【审核失败(业务处理失败)】");
            rxOrderFollow.setContent(sysUser.getNickName() + "对订单操作了审核失败,抖店业务处理失败!" + reviewResponse.getSubMsg());
        }

        rxOrderFollow.setOrderId(rxOrder.getId().intValue());
        rxOrderFollow.setManageId(sysUser.getUserId().intValue());
        rxOrderFollow.setTime(time);
        rxOrderFollowMapper.insertRxOrderFollow(rxOrderFollow);
        rxOrderFollowMapper.insertRxOrderFollow(rxOrderFollow2);
        return AjaxResult.success();
    }


    @PreAuthorize("@ss.hasPermi('hmk:order:getIdentityVisible')")
    @RepeatSubmit
    @PostMapping(value = "/getIdentityVisible")
    public AjaxResult getIdentityVisible(@RequestBody RxOrder rxOrder) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        if (sysUser == null) {
            throw new ServiceException("用户未登录或会话已过期", 401);
        }
        if (StringUtils.isEmpty(sysUser.getNickName())) {
            sysUser = sysUserService.selectUserById(sysUser.getUserId());
        }
        Long time = System.currentTimeMillis() / 1000;
        RxOrder rxOrder1 = rxOrderService.selectRxOrderById(rxOrder.getId());
        RxOrderFollow rxOrderFollow = new RxOrderFollow();
        rxOrderFollow.setTitle("【查看证件号码】");
        rxOrderFollow.setOrderId(rxOrder.getId().intValue());
        rxOrderFollow.setContent(sysUser.getNickName() + "查看了用户证件号码.");
        rxOrderFollow.setTime(time);
        rxOrderFollow.setManageId(sysUser.getUserId().intValue());
        rxOrderFollowMapper.insertRxOrderFollow(rxOrderFollow);
        return AjaxResult.success(rxOrder1);
    }


    @PreAuthorize("@ss.hasPermi('hmk:order:getPhoneVisible')")
    @RepeatSubmit
    @PostMapping(value = "/getPhoneVisible")
    public AjaxResult getPhoneVisible(@RequestBody RxOrder rxOrder) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        if (sysUser == null) {
            throw new ServiceException("用户未登录或会话已过期", 401);
        }
        if (StringUtils.isEmpty(sysUser.getNickName())) {
            sysUser = sysUserService.selectUserById(sysUser.getUserId());
        }
        Long time = System.currentTimeMillis() / 1000;
        RxOrder rxOrder1 = rxOrderService.selectRxOrderById(rxOrder.getId());
        RxOrderFollow rxOrderFollow = new RxOrderFollow();
        rxOrderFollow.setTitle("【查看联系电话】");
        rxOrderFollow.setOrderId(rxOrder.getId().intValue());
        rxOrderFollow.setContent(sysUser.getNickName() + "查看了用户联系电话.");
        rxOrderFollow.setManageId(sysUser.getUserId().intValue());
        rxOrderFollow.setTime(time);
        rxOrderFollowMapper.insertRxOrderFollow(rxOrderFollow);
        return AjaxResult.success(rxOrder1);
    }


    @PreAuthorize("@ss.hasPermi('hmk:order:updateDouDianOrderManageAuthorId')")
    @RepeatSubmit
    @PostMapping(value = "/updateDouDianOrderManageAuthorId")
    public AjaxResult updateDouDianOrderManageAuthorId(@RequestBody RxOrder rxOrder) {
        Long time = System.currentTimeMillis() / 1000;
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        if (sysUser == null) {
            throw new ServiceException("用户未登录或会话已过期", 401);
        }
        if (StringUtils.isEmpty(sysUser.getNickName())) {
            sysUser = sysUserService.selectUserById(sysUser.getUserId());
        }
        RxOrder rxOrder1 = rxOrderService.selectRxOrderById(rxOrder.getId());

        RxOrderFollow rxOrderFollow = new RxOrderFollow();
        String followStr = "";
        if (null == rxOrder1.getDoudianOrderManageAuthorId()) {
            SysUser newUser = sysUserService.selectUserById(Long.valueOf(rxOrder.getDoudianOrderManageAuthorId()));
            if (null != newUser) {
                followStr = sysUser.getNickName() + "将带货达人选择为【" + newUser.getNickName() + "】";
            }
            rxOrderFollow.setTitle("【选择带货达人】");
        } else {
            SysUser oldUser = sysUserService.selectUserById(Long.valueOf(rxOrder1.getDoudianOrderManageAuthorId()));
            SysUser newUser = sysUserService.selectUserById(Long.valueOf(rxOrder.getDoudianOrderManageAuthorId()));
            if (null != oldUser && null != newUser) {
                followStr = sysUser.getNickName() + "将带货达人由【" + oldUser.getNickName() + "】改为【" + newUser.getNickName() + "】";
            }
            rxOrderFollow.setTitle("【修改带货达人】");
        }
        rxOrderFollow.setOrderId(rxOrder.getId().intValue());
        rxOrderFollow.setContent(followStr);
        rxOrderFollow.setTime(time);
        rxOrderFollowMapper.insertRxOrderFollow(rxOrderFollow);
        rxOrderService.updateRxOrder(rxOrder);
        return AjaxResult.success();
    }


    @PreAuthorize("@ss.hasPermi('hmk:order:remove')")

    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(rxOrderService.deleteRxOrderByIds(ids));
    }


    @PreAuthorize("@ss.hasPermi('hmk:order:query')")
    @GetMapping(value = "/getOrderDetailById/{id}")
    public AjaxResult getOrderDetailById(@PathVariable("id") Long id) {

        OrderDetailVo orderDetailVo = rxOrderMapper.getOrderDetailById(id);
        if (StringUtils.isNotEmpty(orderDetailVo.getDoudianOrderUserTagUi2())) {
            List<DoudianOrderUserTag> list = JSONArray.parseArray(orderDetailVo.getDoudianOrderUserTagUi2(), DoudianOrderUserTag.class);
            orderDetailVo.setDoudianOrderUserTagList(list);
        }

        if (StringUtils.isNotEmpty(orderDetailVo.getDoudianOrderSpec())) {
            String jsonStr2 = PhpToJson.phpToJson(orderDetailVo.getDoudianOrderSpec());
            List<DoudianOrderSpec> list2 = JSON.parseArray(jsonStr2, DoudianOrderSpec.class);
            orderDetailVo.setDoudianOrderSpecList(list2);
        }

        if (StringUtils.isEmpty(orderDetailVo.getUserId())) {
            orderDetailVo.setShengId(orderDetailVo.getShengId2());
            orderDetailVo.setCityId(orderDetailVo.getCityId2());
            orderDetailVo.setAreaId(orderDetailVo.getAreaId2());
            orderDetailVo.setRealAddress(orderDetailVo.getRealAddress2());
            orderDetailVo.setContactName(orderDetailVo.getContactName2());
            orderDetailVo.setContactTel(orderDetailVo.getContactTel2());
            orderDetailVo.setUserTel("非会员");
        }
        List<LabelObj> labels = getLabelObjList(orderDetailVo);
        if (StringUtils.isNotEmpty(orderDetailVo.getDefineLabel())) {
            LabelObj labelObj = new LabelObj();
            labelObj.setName(orderDetailVo.getDefineLabel());
            labelObj.setNode(orderDetailVo.getDefineLabelNotes());
            labels.add(labelObj);
        }

        if (StringUtils.isNotEmpty(orderDetailVo.getLabelNotes())) {
            try {
                String jsonStr = PhpToJson.phpToJson(orderDetailVo.getLabelNotes());
                List<LabelNote> l = JSON.parseArray(jsonStr, LabelNote.class);
                orderDetailVo.setLabelNotes(l.get(0).getNotes());
                orderDetailVo.setLabelNoteList(l);
            } catch (Exception e) {
                logger.info("报错", e.getMessage());
            }
        }

        if (StringUtils.isNotEmpty(orderDetailVo.getCustomNumber())) {
            orderDetailVo.setCustomNumberAge(CardNumberUtils.calculateAge(orderDetailVo.getCustomNumber()) + "岁");
        }

        if (StringUtils.isNotEmpty(orderDetailVo.getPayType())) {
            if ("1".equals(orderDetailVo.getPayType())) {
                orderDetailVo.setPayType("微信支付");
            }
            if ("2".equals(orderDetailVo.getPayType())) {
                orderDetailVo.setPayType("支付宝支付");
            }
        }

        orderDetailVo.setLabels(labels);

        if ("6".equals(orderDetailVo.getState())) {
            if (StringUtils.isNotEmpty(orderDetailVo.getCommissionpriceArr())) {
                String phpStr = PhpToJson.phpToJson(orderDetailVo.getCommissionpriceArr());
                List<CommissionNote> commissionNotes = JSONArray.parseArray(phpStr, CommissionNote.class);
                if (null != commissionNotes && commissionNotes.size() > 0) {
                    for (CommissionNote c : commissionNotes) {
                        orderDetailVo.getCommissionpriceArrList().add(c.getName() + "返佣" + c.getLv() + "%");
                    }
                }
            }
        }

        String maskIdNumber = CardNumberUtils.maskIdNumber(orderDetailVo.getCustomNumber());
        orderDetailVo.setCustomNumber(maskIdNumber);
        String maskPhoneNumber = CardNumberUtils.maskPhoneNumber(orderDetailVo.getCustomTel());
        orderDetailVo.setCustomTel(maskPhoneNumber);
        return success(orderDetailVo);
    }


    @PreAuthorize("@ss.hasPermi('hmk:orderFollow:query')")
    @GetMapping(value = "/getOrderFollowDetailById/{id}")
    public AjaxResult getOrderFollowDetailById(@PathVariable("id") Long id) {
        if (null == id) {
            throw new BaseException("getOrderFollowDetailById接口没传id");
        }
        OrderDetailVo orderDetailVo = rxOrderMapper.getOrderDetailById(id);
        if (StringUtils.isNotEmpty(orderDetailVo.getDoudianOrderUserTagUi2())) {
            List<DoudianOrderUserTag> list = JSONArray.parseArray(orderDetailVo.getDoudianOrderUserTagUi2(), DoudianOrderUserTag.class);
            orderDetailVo.setDoudianOrderUserTagList(list);
        }

        if (StringUtils.isNotEmpty(orderDetailVo.getDoudianOrderSpec())) {
            String jsonStr2 = PhpToJson.phpToJson(orderDetailVo.getDoudianOrderSpec());
            List<DoudianOrderSpec> list2 = JSON.parseArray(jsonStr2, DoudianOrderSpec.class);
            orderDetailVo.setDoudianOrderSpecList(list2);
        }

        if (StringUtils.isEmpty(orderDetailVo.getUserId())) {
            orderDetailVo.setShengId(orderDetailVo.getShengId2());
            orderDetailVo.setCityId(orderDetailVo.getCityId2());
            orderDetailVo.setAreaId(orderDetailVo.getAreaId2());
            orderDetailVo.setRealAddress(orderDetailVo.getRealAddress2());
            orderDetailVo.setContactName(orderDetailVo.getContactName2());
            orderDetailVo.setContactTel(orderDetailVo.getContactTel2());
            orderDetailVo.setUserTel("非会员");
        }
        List<LabelObj> labels = getLabelObjList(orderDetailVo);
        if (StringUtils.isNotEmpty(orderDetailVo.getDefineLabel())) {
            LabelObj labelObj = new LabelObj();
            labelObj.setName(orderDetailVo.getDefineLabel());
            labelObj.setNode(orderDetailVo.getDefineLabelNotes());
            labels.add(labelObj);
        }

        if (StringUtils.isNotEmpty(orderDetailVo.getLabelNotes())) {
            try {
                String jsonStr = PhpToJson.phpToJson(orderDetailVo.getLabelNotes());
                List<LabelNote> l = JSON.parseArray(jsonStr, LabelNote.class);
                orderDetailVo.setLabelNotes(l.get(0).getNotes());
                orderDetailVo.setLabelNoteList(l);
            } catch (Exception e) {
                logger.info("报错", e.getMessage());
            }
        }
        if (StringUtils.isNotEmpty(orderDetailVo.getCustomNumber())) {
            orderDetailVo.setCustomNumberAge(CardNumberUtils.calculateAge(orderDetailVo.getCustomNumber()) + "岁");
        }
        if (StringUtils.isNotEmpty(orderDetailVo.getPayType())) {
            if ("1".equals(orderDetailVo.getPayType())) {
                orderDetailVo.setPayType("微信支付");
            }
            if ("2".equals(orderDetailVo.getPayType())) {
                orderDetailVo.setPayType("支付宝支付");
            }
        }
        orderDetailVo.setLabels(labels);
        if ("6".equals(orderDetailVo.getState())) {
            if (StringUtils.isNotEmpty(orderDetailVo.getCommissionpriceArr())) {
                String phpStr = PhpToJson.phpToJson(orderDetailVo.getCommissionpriceArr());
                List<CommissionNote> commissionNotes = JSONArray.parseArray(phpStr, CommissionNote.class);
                if (null != commissionNotes && commissionNotes.size() > 0) {
                    for (CommissionNote c : commissionNotes) {

                        orderDetailVo.getCommissionpriceArrList().add(c.getName() + "返佣" + c.getLv() + "%");
                    }
                }
            }
        }
        String maskIdNumber = CardNumberUtils.maskIdNumber(orderDetailVo.getCustomNumber());
        orderDetailVo.setCustomNumber(maskIdNumber);
        String maskPhoneNumber = CardNumberUtils.maskPhoneNumber(orderDetailVo.getCustomTel());
        orderDetailVo.setCustomTel(maskPhoneNumber);
        if (StringUtils.isNotEmpty(orderDetailVo.getSupplierName())) {
            orderDetailVo.setSupplierName("******");
        }
        KsOrder ksOrder = kOM.selectKsOrderBySerial(orderDetailVo.getSerial());
        if (null != ksOrder) {
            orderDetailVo.setKsOrder(ksOrder);
        }
        return success(orderDetailVo);
    }

    private List<LabelObj> getLabelObjList2(RxOrderVo orderDetailVo) {
        List<LabelObj> labels = new ArrayList<>();
        String labelType = orderDetailVo.getLabelType();
        if (StringUtils.isNotEmpty(orderDetailVo.getChannelName())) {
            LabelObj labelObj = new LabelObj();
            labelObj.setName(orderDetailVo.getChannelName());
            labelObj.setNode(orderDetailVo.getContactUser());
            labels.add(labelObj);
        }

        if (StringUtils.isNotEmpty(labelType)) {
            List<LabelNote> labelNotes = null;
            if (StringUtils.isNotEmpty(orderDetailVo.getLabelNotes())) {
                String labelNodeStr = PhpToJson.phpToJson(orderDetailVo.getLabelNotes());
                labelNotes = JSON.parseArray(labelNodeStr, LabelNote.class);
            }
            String[] labelTypes = labelType.split(",");

            for (int i = 0; i < labelTypes.length; i++) {
                if ("1".equals(labelTypes[i])) {
                    LabelObj labelObj = new LabelObj();
                    labelObj.setName("宽");
                    labels.add(labelObj);
                    if (null != labelNotes) {
                        LabelNote labelNote = labelNotes.stream().filter(item -> item.getType().equals("1")).findFirst().get();
                        labelObj.setNode(labelNote.getNotes());
                    }
                } else if ("2".equals(labelTypes[i])) {
                    LabelObj labelObj = new LabelObj();
                    labelObj.setName("白");
                    labels.add(labelObj);
                    if (null != labelNotes) {
                        LabelNote labelNote = labelNotes.stream().filter(item -> item.getType().equals("2")).findFirst().get();
                        labelObj.setNode(labelNote.getNotes());
                    }
                } else if ("3".equals(labelTypes[i])) {
                    LabelObj labelObj = new LabelObj();
                    labelObj.setName("黑");
                    labels.add(labelObj);
                    if (null != labelNotes) {
                        LabelNote labelNote = labelNotes.stream().filter(item -> item.getType().equals("3")).findFirst().get();
                        labelObj.setNode(labelNote.getNotes());
                    }
                } else if ("4".equals(labelTypes[i])) {
                    LabelObj labelObj = new LabelObj();
                    labelObj.setName("维");
                    labels.add(labelObj);
                    if (null != labelNotes) {
                        LabelNote labelNote = labelNotes.stream().filter(item -> item.getType().equals("4")).findFirst().get();
                        labelObj.setNode(labelNote.getNotes());
                    }
                }
            }

            if (StringUtils.isNotEmpty(orderDetailVo.getHjfLabelNotes()) && orderDetailVo.getIsActivation() != 2) {
                List<LabelNote> hjfLabelNotes = JSONArray.parseArray(orderDetailVo.getHjfLabelNotes(), LabelNote.class);
                if (!CollectionUtils.isEmpty(hjfLabelNotes)) {
                    for (LabelNote l : hjfLabelNotes) {
                        if ("1".equals(l.getType())) {
                            LabelObj labelObj = new LabelObj();
                            labelObj.setName(orderDetailVo.getAreaId() + "宽带");
                            labelObj.setNode(l.getNotes());
                            labels.add(labelObj);
                        }
                    }
                }
            }
        }

        if (null != orderDetailVo.getEvidenceChainTag() && "0".equals(orderDetailVo.getEvidenceChainTag()) && ("7".equals(orderDetailVo.getState()) || "8".equals(orderDetailVo.getState()))) {
            LabelObj labelObj = new LabelObj();
            labelObj.setName("缺失证据链");
            labelObj.setNode("");
            labels.add(labelObj);
        }

        return labels;
    }

    private List<LabelObj> getLabelObjList(OrderDetailVo orderDetailVo) {
        List<LabelObj> labels = new ArrayList<>();
        String labelType = orderDetailVo.getLabelType();
        if (StringUtils.isNotEmpty(orderDetailVo.getChannelName())) {
            LabelObj labelObj = new LabelObj();
            labelObj.setName(orderDetailVo.getChannelName());
            labelObj.setNode(orderDetailVo.getContactUser());
            labels.add(labelObj);
        }
        if (StringUtils.isNotEmpty(labelType)) {
            List<LabelNote> labelNotes = null;
            if (StringUtils.isNotEmpty(orderDetailVo.getLabelNotes())) {
                String labelNodeStr = PhpToJson.phpToJson(orderDetailVo.getLabelNotes());
                labelNotes = JSON.parseArray(labelNodeStr, LabelNote.class);
            }
            String[] labelTypes = labelType.split(",");
            for (int i = 0; i < labelTypes.length; i++) {
                if ("1".equals(labelTypes[i])) {
                    LabelObj labelObj = new LabelObj();
                    labelObj.setName("宽");
                    labels.add(labelObj);
                    if (null != labelNotes) {
                        LabelNote labelNote = labelNotes.stream().filter(item -> item.getType().equals("1")).findFirst().get();
                        labelObj.setNode(labelNote.getNotes());
                    }
                } else if ("2".equals(labelTypes[i])) {
                    LabelObj labelObj = new LabelObj();
                    labelObj.setName("白");
                    labels.add(labelObj);
                    if (null != labelNotes) {
                        LabelNote labelNote = labelNotes.stream().filter(item -> item.getType().equals("2")).findFirst().get();
                        labelObj.setNode(labelNote.getNotes());
                    }
                } else if ("3".equals(labelTypes[i])) {
                    LabelObj labelObj = new LabelObj();
                    labelObj.setName("黑");
                    labels.add(labelObj);
                    if (null != labelNotes) {
                        LabelNote labelNote = labelNotes.stream().filter(item -> item.getType().equals("3")).findFirst().get();
                        labelObj.setNode(labelNote.getNotes());
                    }
                } else if ("4".equals(labelTypes[i])) {
                    LabelObj labelObj = new LabelObj();
                    labelObj.setName("维");
                    labels.add(labelObj);
                    if (null != labelNotes) {
                        LabelNote labelNote = labelNotes.stream().filter(item -> item.getType().equals("4")).findFirst().get();
                        labelObj.setNode(labelNote.getNotes());
                    }
                }
            }
            if (StringUtils.isNotEmpty(orderDetailVo.getHjfLabelNotes()) && orderDetailVo.getIsActivation() != 2) {
                List<LabelNote> hjfLabelNotes = JSONArray.parseArray(orderDetailVo.getHjfLabelNotes(), LabelNote.class);
                if (!CollectionUtils.isEmpty(hjfLabelNotes)) {
                    for (LabelNote l : hjfLabelNotes) {
                        if ("1".equals(l.getType())) {
                            LabelObj labelObj = new LabelObj();
                            labelObj.setName(orderDetailVo.getAreaId() + "宽带");
                            labelObj.setNode(l.getNotes());
                            labels.add(labelObj);
                        }
                    }
                }
            }
        }
        return labels;
    }


    public static void jieSuanJia(RxTel rxTel, RxOrder rxOrder, RxBusiness business) {
        if (null != business) {
            BigDecimal number = new BigDecimal(business.getDiscount());
            BigDecimal divisor = new BigDecimal("10");
            BigDecimal discount = number.divide(divisor, 2, BigDecimal.ROUND_HALF_EVEN);
            BigDecimal settlement1 = new BigDecimal(rxTel.getPrice()).multiply(discount);
            BigDecimal settlement2 = new BigDecimal(rxTel.getFloorprice());
            BigDecimal maxSettlement;
            if (settlement1.compareTo(settlement2) > 0) {
                maxSettlement = settlement1;
            } else {
                maxSettlement = settlement2;
            }
            rxOrder.setSettlementprice(maxSettlement);
        }
    }

    public void addOrderRemark(String douDianOrderId, String phone, AccessToken token) {
        OrderAddOrderRemarkRequest request = new OrderAddOrderRemarkRequest();
        OrderAddOrderRemarkParam param = request.getParam();
        param.setOrderId(douDianOrderId);
        param.setRemark(phone);
        param.setIsAddStar("true");
        param.setStar("4");
        OrderAddOrderRemarkResponse response = request.execute(token);
    }


    @PreAuthorize("@ss.hasPermi('hmk:order:getSupplierTitle')")
    @PostMapping(value = "/getSupplierTitle")
    public AjaxResult getSupplierTitle(@RequestBody RxOrderVo rxOrder) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        if (sysUser == null) {
            throw new ServiceException("用户未登录或会话已过期", 401);
        }
        if (StringUtils.isEmpty(sysUser.getNickName())) {
            sysUser = sysUserService.selectUserById(sysUser.getUserId());
        }
        Long time = System.currentTimeMillis() / 1000;
        RxOrderFollow rxOrderFollow = new RxOrderFollow();
        rxOrderFollow.setTitle("【查看号码仓】");
        rxOrderFollow.setOrderId(Integer.valueOf(rxOrder.getId()));
        rxOrderFollow.setContent(sysUser.getNickName() + "查看了号码仓.");
        rxOrderFollow.setManageId(sysUser.getUserId().intValue());
        rxOrderFollow.setTime(time);
        rxOrderFollowMapper.insertRxOrderFollow(rxOrderFollow);
        return success(rxSupplierService.selectRxSupplierById(Long.valueOf(rxOrder.getTitle())));
    }


    @PreAuthorize("@ss.hasPermi('hmk:order:getSupplierNameVisible')")
    @RepeatSubmit
    @PostMapping(value = "/getSupplierNameVisible")
    public AjaxResult getSupplierNameVisible(@RequestBody RxOrder rxOrder) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        if (sysUser == null) {
            throw new ServiceException("用户未登录或会话已过期", 401);
        }
        if (StringUtils.isEmpty(sysUser.getNickName())) {
            sysUser = sysUserService.selectUserById(sysUser.getUserId());
        }
        Long time = System.currentTimeMillis() / 1000;
        OrderDetailVo orderDetailVo = rxOrderMapper.getOrderDetailById(rxOrder.getId());
        RxOrderFollow rxOrderFollow = new RxOrderFollow();
        rxOrderFollow.setTitle("【查看号码仓】");
        rxOrderFollow.setOrderId(rxOrder.getId().intValue());
        rxOrderFollow.setContent(sysUser.getNickName() + "查看了号码仓.");
        rxOrderFollow.setManageId(sysUser.getUserId().intValue());
        rxOrderFollow.setTime(time);
        rxOrderFollowMapper.insertRxOrderFollow(rxOrderFollow);
        return AjaxResult.success(orderDetailVo);
    }


    @PermitAll
    @GetMapping("/orderChannelSimpleList")
    public AjaxResult list(OrderChannel orderChannel) {
        List<OrderChannel> list = orderChannelService.selectOrderChannelList(orderChannel);
        return AjaxResult.success(list);
    }


    @PermitAll
    @GetMapping("/douDianGoodsList")
    public AjaxResult doudianGoodsList(RxDoudianGoods rxDoudianGoods) {
        List<RxDoudianGoods> list = rxDoudianGoodsMapper.selectRxDoudianGoodsList(rxDoudianGoods);
        return AjaxResult.success(list);
    }


    @PreAuthorize("@ss.hasPermi('hmk:order:addKsOrderReplyLogAndUpload')")
    @PostMapping("/addKsOrderReplyLogAndUpload")
    @RepeatSubmit
    public AjaxResult addKsOrderReplyLogAndUpload(@RequestPart(value = "files", required = false) List<MultipartFile> files,
                                                  @RequestPart(value = "audioFiles", required = false)
                                                  List<MultipartFile> audioFiles, String orderId, Long ksId,
                                                  String replyContent, Long referenceId, String referenceContent, Integer state) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        if (sysUser == null) {
            throw new ServiceException("用户未登录或会话已过期", 401);
        }
        if (StringUtils.isEmpty(sysUser.getNickName())) {
            sysUser = sysUserService.selectUserById(sysUser.getUserId());
        }
        KsOrder ksOrder = new KsOrder();
        KsOrder oldKsOrder = kOM.selectKsOrderById(ksId);
        KsReplyLog queryReplyLog = new KsReplyLog();
        queryReplyLog.setKsId(ksId);
        List<KsReplyLog> ksReplyLogs = kRLM.selectKsReplyLogList(queryReplyLog);
        if (ksReplyLogs.size() >= 2 && oldKsOrder.getSupportId() == sysUser.getUserId() && 0 == oldKsOrder.getSupportIsRes()) {
            state = 2;
            ksOrder.setSupportIsRes(1);
        }

        Date createDate = new Date();
        KsReplyLog ksReplyLog = new KsReplyLog();
        ksReplyLog.setOrderId(orderId);
        ksReplyLog.setKsId(ksId);
        ksReplyLog.setReplyContent(replyContent);
        ksReplyLog.setReferenceId(referenceId);
        ksReplyLog.setReferenceContent(referenceContent);
        ksReplyLog.setReplyUserId(sysUser.getUserId());
        ksReplyLog.setCreateTime(createDate);
        kRLM.insertKsReplyLog(ksReplyLog);

        List<String> failedFiles = new ArrayList<>();
        if (null != files) {
            final List<String> ALLOWED_EXTENSIONS = Arrays.asList(".jpg", ".jpeg", ".png");
            for (MultipartFile file : files) {
                try {
                    String originalFilename = file.getOriginalFilename();
                    if (originalFilename == null || !checkFileType(originalFilename, ALLOWED_EXTENSIONS)) {
                        failedFiles.add(originalFilename + "（文件类型不支持）");
                        continue;
                    }
                    String fileName = "images/" + DateUtils.dateTimeNowMillis() + "-" + file.getOriginalFilename();
                    ossClient.putObject("cqhmk", fileName, file.getInputStream());
                    String url = fileName;
                    KsAttachment ka = new KsAttachment();
                    ka.setOrderId(ksReplyLog.getOrderId());
                    ka.setKsId(ksId);
                    ka.setKsReplyId(ksReplyLog.getId());
                    ka.setUserId(sysUser.getUserId());
                    ka.setFileType("1");
                    ka.setObjectPath(fileName);
                    ka.setCreateTime(createDate);
                    kAM.insertKsAttachment(ka);
                } catch (IOException e) {
                    failedFiles.add(file.getOriginalFilename());
                }
            }
        }

        if (null != audioFiles) {
            final List<String> AUDIO_ALLOWED_EXTENSIONS = Arrays.asList(".mp3", ".wav", ".m4a");
            for (MultipartFile file : audioFiles) {
                try {
                    String originalFilename = file.getOriginalFilename();
                    if (originalFilename == null || !checkFileType(originalFilename, AUDIO_ALLOWED_EXTENSIONS)) {
                        failedFiles.add(originalFilename + "（文件类型不支持）");
                        continue;
                    }
                    String fileName = "audio/" + DateUtils.dateTimeNowMillis() + "-" + file.getOriginalFilename();
                    ossClient.putObject("cqhmk", fileName, file.getInputStream());
                    String url = fileName;
                    KsAttachment ka = new KsAttachment();
                    ka.setOrderId(ksReplyLog.getOrderId());
                    ka.setKsId(ksId);
                    ka.setKsReplyId(ksReplyLog.getId());
                    ka.setUserId(sysUser.getUserId());
                    ka.setFileType("2");
                    ka.setObjectPath(fileName);
                    ka.setCreateTime(createDate);
                    kAM.insertKsAttachment(ka);
                } catch (IOException e) {
                    failedFiles.add(file.getOriginalFilename());
                }
            }
        }
        if (null != state && state > 0) {

            if (state == 6) {
                ksOrder.setCloseTime(createDate);
                String timeDistance = DateUtils.timeDistance(createDate, oldKsOrder.getCreateTime());
                KsReplyLog ksR5 = new KsReplyLog();
                ksR5.setOrderId(orderId);
                ksR5.setKsId(ksId);
                ksR5.setReplyContent("【关闭客诉工单】" + sysUser.getNickName() + "关闭了客诉工单，处理时长" + timeDistance + ".关闭原因:" + replyContent);
                ksR5.setReplyUserId(sysUser.getUserId());
                ksR5.setCreateTime(createDate);
                kRLM.insertKsReplyLog(ksR5);

                RxOrderFollow rxOrderFollow = new RxOrderFollow();
                rxOrderFollow.setTitle("【关闭客诉工单】");
                OrderDetailVo orderDetailVo = rxOrderMapper.selectRxOrderBySerial(orderId);
                rxOrderFollow.setOrderId(orderDetailVo.getId().intValue());
                rxOrderFollow.setContent(sysUser.getNickName() + "关闭了客诉工单，处理时长" + timeDistance + ".关闭原因:" + replyContent);
                rxOrderFollow.setManageId(sysUser.getUserId().intValue());
                rxOrderFollow.setTime(System.currentTimeMillis() / 1000);
                rxOrderFollowMapper.insertRxOrderFollow(rxOrderFollow);
            }
            if (state == 5) {
                ksOrder.setWanJieTime(createDate);
                String timeDistance = DateUtils.timeDistance(createDate, oldKsOrder.getCreateTime());
                KsReplyLog ksR4 = new KsReplyLog();
                ksR4.setOrderId(orderId);
                ksR4.setKsId(ksId);
                ksR4.setReplyContent("【完结客诉工单】" + sysUser.getNickName() + "完结了客诉工单，处理时长" + timeDistance + ".完结备注:" + replyContent);
                ksR4.setReplyUserId(sysUser.getUserId());
                ksR4.setCreateTime(createDate);
                kRLM.insertKsReplyLog(ksR4);

                RxOrderFollow rxOrderFollow = new RxOrderFollow();
                rxOrderFollow.setTitle("【完结客诉工单】");
                OrderDetailVo orderDetailVo = rxOrderMapper.selectRxOrderBySerial(orderId);
                rxOrderFollow.setOrderId(orderDetailVo.getId().intValue());
                rxOrderFollow.setContent(sysUser.getNickName() + "完结了客诉工单，处理时长" + timeDistance + ".完结备注:" + replyContent);
                rxOrderFollow.setManageId(sysUser.getUserId().intValue());
                rxOrderFollow.setTime(System.currentTimeMillis() / 1000);
                rxOrderFollowMapper.insertRxOrderFollow(rxOrderFollow);
            }
            ksOrder.setId(ksId);
            ksOrder.setState(state);
            ksOrder.setUpdateTime(createDate);
            ksOrder.setUpdateBy(sysUser.getUserId().toString());
            kOM.updateKsOrder(ksOrder);
        }
        return AjaxResult.success();
    }


    @PreAuthorize("@ss.hasPermi('hmk:order:ksAddAuditUserId')")
    @PostMapping("/ksAddAuditUserId")
    public AjaxResult ksAuditFormConfirm(@RequestBody KsReplyLog ksReplyLog) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        if (sysUser == null) {
            throw new ServiceException("用户未登录或会话已过期", 401);
        }
        if (StringUtils.isEmpty(sysUser.getNickName())) {
            sysUser = sysUserService.selectUserById(sysUser.getUserId());
        }
        String replyContent = ksReplyLog.getReplyContent();
        Date createDate = new Date();
        if (null == ksReplyLog.getAuditUserId()) {
            ksReplyLog.setReplyContent("【添加处理方案】" + sysUser.getNickName() + "添加了处理方案:" + replyContent);
        } else {
            SysUser auditUser = sysUserService.selectUserById(ksReplyLog.getAuditUserId());
            ksReplyLog.setReplyContent("【添加处理方案，等待审核】" + sysUser.getNickName() + "添加了处理方案，等待" + auditUser.getNickName() + "审核:" + replyContent);
        }
        ksReplyLog.setOrderId(ksReplyLog.getOrderId());
        ksReplyLog.setKsId(ksReplyLog.getKsId());
        ksReplyLog.setReplyUserId(sysUser.getUserId());
        ksReplyLog.setCreateTime(createDate);
        kRLM.insertKsReplyLog(ksReplyLog);
        KsOrder ksOrder = new KsOrder();
        ksOrder.setId(ksReplyLog.getKsId());
        ksOrder.setState(3);
        if (null != ksReplyLog.getAuditUserId()) {
            ksOrder.setAuditUser(ksReplyLog.getAuditUserId());
        }
        ksOrder.setUpdateTime(createDate);
        ksOrder.setUpdateBy(sysUser.getUserId().toString());
        if (null == ksReplyLog.getAuditUserId()) {
            ksOrder.setState(4);
        }
        kOM.updateKsOrder(ksOrder);
        KsOrder oldKsOrder = kOM.selectKsOrderById(ksReplyLog.getKsId());
        if (null != ksReplyLog.getAuditUserId()) {
            KsLetter ksLetter = new KsLetter();
            ksLetter.setKsId(oldKsOrder.getKsId());
            ksLetter.setKsContent(oldKsOrder.getContent());
            ksLetter.setOrderId(oldKsOrder.getOrderId());
            ksLetter.setIssuerUser(sysUser.getUserId());
            ksLetter.setAuditUser(ksReplyLog.getAuditUserId());
            ksLetter.setTitle(oldKsOrder.getTitle());
            ksLetter.setIssuerContent(replyContent);
            ksLetter.setIssuerTime(createDate);
            ksLetter.setIsAgree(0L);
            ksLetterMapper.insertKsLetter(ksLetter);
        }
        return AjaxResult.success();
    }


    @PreAuthorize("@ss.hasPermi('hmk:order:ossUpload')")
    @PostMapping("/images/upload")
    public AjaxResult uploadImages(@RequestParam("files") List<MultipartFile> files, Long orderId, Long followId, Long userId) {
        if (null == orderId) {
            throw new ServiceException("订单id必传");
        }
        if (null == followId) {
            throw new ServiceException("订单跟进id必传");
        }
        if (null == userId) {
            throw new ServiceException("上传用户id必传");
        }

        if (files.size() == 0) {
            throw new ServiceException("请选择图片上传");
        }
        final List<String> ALLOWED_EXTENSIONS = Arrays.asList(".jpg", ".jpeg", ".png");
        Map<String, Object> result = new HashMap<>();
        List<String> urls = new ArrayList<>();
        List<String> failedFiles = new ArrayList<>();
        Date createDate = new Date();
        for (MultipartFile file : files) {
            try {
                String originalFilename = file.getOriginalFilename();
                if (originalFilename == null || !checkFileType(originalFilename, ALLOWED_EXTENSIONS)) {
                    failedFiles.add(originalFilename + "（文件类型不支持）");
                    continue;
                }
                String fileName = "images/" + DateUtils.dateTimeNowMillis() + "-" + file.getOriginalFilename();
                ossClient.putObject("cqhmk", fileName, file.getInputStream());
                String url = fileName;
                OrderAttachment oa = new OrderAttachment();
                oa.setFileType("1");
                oa.setOrderId(orderId);
                oa.setOrderFollow(followId);
                oa.setUserId(userId);
                oa.setObjectPath(fileName);
                oa.setCreateTime(createDate);
                oAM.insertOrderAttachment(oa);
                urls.add(url);
            } catch (IOException e) {
                failedFiles.add(file.getOriginalFilename());
            }
        }
        RxOrder ro = new RxOrder();
        ro.setId(orderId);
        ro.setEvidenceChainTag("1");
        rxOrderMapper.updateRxOrder(ro);
        result.put("success", true);
        result.put("urls", urls);
        if (!failedFiles.isEmpty()) {
            result.put("failed", failedFiles);
            result.put("success", false);
        }
        return AjaxResult.success(result);
    }


    @PreAuthorize("@ss.hasPermi('hmk:order:ossUpload')")
    @PostMapping("/audio/upload")
    public AjaxResult uploadAudio(@RequestParam("files") List<MultipartFile> files, Long orderId, Long followId, Long userId) {
        if (null == orderId) {
            throw new ServiceException("订单id必传");
        }
        if (null == followId) {
            throw new ServiceException("订单跟进id必传");
        }
        if (null == userId) {
            throw new ServiceException("上传用户id必传");
        }
        if (files.size() == 0) {
            throw new ServiceException("请选择音频文件上传");
        }
        final List<String> ALLOWED_EXTENSIONS = Arrays.asList(".mp3", ".wav", ".m4a");
        Map<String, Object> result = new HashMap<>();
        List<String> urls = new ArrayList<>();
        List<String> failedFiles = new ArrayList<>();
        Date createDate = new Date();
        for (MultipartFile file : files) {
            try {
                String originalFilename = file.getOriginalFilename();
                if (originalFilename == null || !checkFileType(originalFilename, ALLOWED_EXTENSIONS)) {
                    failedFiles.add(originalFilename + "（文件类型不支持）");
                    continue;
                }
                String fileName = "audio/" + DateUtils.dateTimeNowMillis() + "-" + file.getOriginalFilename();
                ossClient.putObject("cqhmk", fileName, file.getInputStream());
                String url = fileName;
                OrderAttachment oa = new OrderAttachment();
                oa.setFileType("2");
                oa.setOrderId(orderId);
                oa.setOrderFollow(followId);
                oa.setUserId(userId);
                oa.setObjectPath(fileName);
                oa.setCreateTime(createDate);
                oAM.insertOrderAttachment(oa);
                urls.add(url);
            } catch (IOException e) {
                failedFiles.add(file.getOriginalFilename());
            }
        }
        RxOrder ro = new RxOrder();
        ro.setId(orderId);
        ro.setEvidenceChainTag("1");
        rxOrderMapper.updateRxOrder(ro);
        result.put("success", true);
        result.put("urls", urls);
        if (!failedFiles.isEmpty()) {
            result.put("failed", failedFiles);
            result.put("success", false);
        }
        return AjaxResult.success(result);
    }

    @PreAuthorize("@ss.hasPermi('hmk:order:getAttachmentImagesByFollowId')")
    @GetMapping("/getAttachmentImagesByFollowId")
    public AjaxResult getAttachmentImagesByFollowId(Long followId, String fileType) {
        if (null == followId) {
            throw new ServiceException("跟进记录id必传!");
        }
        if (StringUtils.isEmpty(fileType)) {
            throw new ServiceException("文件类型必传!");
        }
        OrderAttachment oa = new OrderAttachment();
        oa.setOrderFollow(followId);
        oa.setFileType(fileType);
        List<OrderAttachment> orderAttachments = oAM.selectOrderAttachmentList(oa);
        if (orderAttachments.size() > 0) {
            orderAttachments.forEach(oa2 -> {
                if (StringUtils.isNotEmpty(oa2.getObjectPath())) {
                    oa2.setFullPath(this.getTempUrl(oa2));
                }
            });
        }
        return AjaxResult.success(orderAttachments);
    }

    @PermitAll
    @PostMapping("/images/getTempUrl")
    public String getTempUrl(@RequestBody OrderAttachment oA) {
        if (StringUtils.isEmpty(oA.getObjectPath())) {
            throw new ServiceException("文件路径必传");
        }
        Date expiration = new Date(System.currentTimeMillis() + 8 * 60 * 60 * 1000);
        GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest("cqhmk", oA.getObjectPath(), HttpMethod.GET);
        request.setExpiration(expiration);
        request.addQueryParameter("response-content-disposition", "inline");
        String tempUrl = ossClient.generatePresignedUrl(request).toString();
        System.out.println(tempUrl);
        return tempUrl;
    }

    @PermitAll
    @PostMapping("/images/getKsTempUrl")
    public AjaxResult getKsTempUrl(@RequestBody List<KsAttachment> kAs) {
        Date expiration = new Date(System.currentTimeMillis() + 8 * 60 * 60 * 1000);
        for (KsAttachment ks : kAs) {
            if (StringUtils.isEmpty(ks.getObjectPath())) {
                throw new ServiceException("文件路径必传");
            }
            GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest("cqhmk", ks.getObjectPath(), HttpMethod.GET);
            request.setExpiration(expiration);
            request.addQueryParameter("response-content-disposition", "inline");
            String tempUrl = ossClient.generatePresignedUrl(request).toString();
            ks.setFullPath(tempUrl);
        }
        return AjaxResult.success(kAs);
    }


    @PreAuthorize("@ss.hasPermi('hmk:order:deleteAttachment')")
    @PostMapping("/deleteAttachment")
    public AjaxResult deleteImage(@RequestBody OrderAttachment oA) {
        if (null == oA.getId()) {
            throw new ServiceException("id必传");
        }
        OrderAttachment orderAttachment = oAM.selectOrderAttachmentById(oA.getId());
        if (null == orderAttachment) {
            throw new ServiceException("未查到该附件!");
        }
        oAM.deleteOrderAttachmentById(oA.getId());
        OrderAttachment query = new OrderAttachment();
        query.setOrderId(orderAttachment.getOrderId());
        List<OrderAttachment> oldOA = oAM.selectOrderAttachmentList(query);
        if (null == oldOA || oldOA.size() == 0) {
            RxOrder ro = new RxOrder();
            ro.setId(orderAttachment.getOrderId());
            ro.setEvidenceChainTag("0");
            rxOrderMapper.updateRxOrder(ro);
        }
        ossClient.deleteObject("cqhmk", orderAttachment.getObjectPath());
        return AjaxResult.success();
    }

    @PreAuthorize("@ss.hasPermi('hmk:order:ksDeleteAttachment')")
    @PostMapping("/ksDeleteAttachment")
    public AjaxResult ksDeleteAttachment(@RequestBody OrderAttachment oA) {
        if (null == oA.getId()) {
            throw new ServiceException("id必传");
        }
        KsAttachment ksAttachment = kAM.selectKsAttachmentById(oA.getId());
        if (null == ksAttachment) {
            throw new ServiceException("未查到该附件!");
        }
        kAM.deleteKsAttachmentById(oA.getId());
        ossClient.deleteObject("cqhmk", ksAttachment.getObjectPath());
        return AjaxResult.success();
    }


    private boolean checkFileType(String filename, List<String> allowedExtensions) {
        String extension = filename.substring(filename.lastIndexOf(".")).toLowerCase();
        return allowedExtensions.contains(extension);
    }
}
